每日5题(4)
(1)机器人的运动范围
//机器人的运动范围
class Solution{
public :
int get_num(pair<int, int> p){//求坐标的数位和
int s = 0;
while (p.first){
s += p.first % 10;
p.first /= 10;
}
while (p.second){
s += p.second % 10;
p.second /= 10;
}
return s;
}
int movingCount(int threshold, int rows, int cols){
if (!rows || !cols){ return 0; }
queue<pair<int, int>>q;
q.push({ 0, 0 });
int fx[4] = { -1, 0, 1, 0 };
int fy[4] = { 0, 1, 0, -1 };
int res = 0;
vector<vector<bool>>st(rows, vector<bool>(cols, false));
while (q.size()){
auto t = q.front();
q.pop();
if (st[t.first][t.second] || get_num(t) > threshold){
continue;
}
res++;
st[t.first][t.second] = true;
for (int i = 0; i < 4; i++){
int x = t.first + fx[i];
int y = t.second + fy[i];
if (x >= 0 && x < rows&&y >= 0 && y < cols){
q.push({ x, y });
}
}
}
return res;
}
};
(2)
给定一个长度为 n 的整数数组 nums,数组中所有的数字都在 0∼n−1 的范围内。
数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。
请找出数组中任意一个重复的数字。
注意:如果某些数字不在 0∼n−1 的范围内,或数组中不包含重复数字,则返回 -1
class Solution {
public:
int duplicateInArray(vector<int>& nums) {
for(int i=0;i<nums.size();i++){
if(nums[i]<0||nums[i]>=nums.size()){
return -1;
}
}
for(int i=0;i<nums.size();i++){
while(nums[nums[i]]!=nums[i]){
swap(nums[nums[i]],nums[i]);
}
if(nums[i]!=i){
return nums[i];
}
}
return -1;
}
};
(3)给定了单链表要删除结点的指针node,在O(1)将该节点删除,
可以将下一个节点的值赋值到node节点,然后删除下一个节点,这样可以拿到实际要删除节点的前驱节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void deleteNode(ListNode* node) {
auto p=node->next;
node->val=p->val;
node->next=p->next;
delete(p);
}
};
(4)输入一个数组,将数组中的奇数都放在数组左边,将数组的偶数都放在右边,
双指针法:左指针向右遍历,找到第一个偶数,右指针向左遍历,找到第一个奇数
class Solution {
public:
void reOrderArray(vector<int> &array) {
//一次遍历法
/* int pos=0;
for(int i=0;i<array.size();i++){
if(array[i]&1){
swap(array[pos++],array[i]);
}
}*/
//双指针法
int l=0,r=array.size()-1;
while(l<r){
while(l<r&&(array[l]&1)){
l++;
}
while(l<r&&(!(array[r]&1))){
r--;
}
if(l<r){
swap(array[l],array[r]);
}
}
}
};
(5)
求1+2+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
class Solution {
public:
int getSum(int n) {
//递推方式
/*int result=n;
(n>0)&&(result+=getSum(n-1));
return result;*/
char a[n][n+1];
return sizeof(a)>>1;
}
};
(6)构建乘积数组
B[i]=A[0]*.....A[i-1]*A[i+1]*...A[n-1]
//构建乘积数组
class Solution{
public:
vector<int> * multiply(const vector<int> &A){
if (A.empty()){
return vector<int>();
}
int n = A.size();
vector<int>B(n);
for (int i = 0, tmp = 1; i < n; i++){
B[i] = tmp;
tmp *= A[i];
}
for (int i = n - 1, tmp = 1; i >= 0; i--){
B[i] *= tmp;
tmp *= A[i];
}
return B;
}
};

浙公网安备 33010602011771号