顺序表是最基础的数组结构,所有数据都按顺序存储。
第一题 1464. 数组中两元素的最大乘积
https://leetcode.cn/problems/maximum-product-of-two-elements-in-an-array/description/
第一种:常规解法,遍历两次数组根据条件比较出最大的即可
int maxProduct(int* nums, int numsSize) {int max = 0;for(int i = 0; i < numsSize - 1; ++i) {for(int j = i + 1; j < numsSize; ++j) {int temp = (nums[i] - 1) * (nums[j] - 1);if(temp > max) max = temp;}}return max;
}
第二种:使用排序,先排序数组,然后直接将最大的和次大的做运算得出结果。
int cmp(const void * p1, const void *p2) {return (*(int *) p1) - (* (int *) p2);
}int maxProduct(int* nums, int numsSize) {qsort(nums, numsSize, sizeof(int), cmp);return (nums[numsSize - 1] - 1) * (nums[numsSize -2] - 1);
}
第二题 485. 最大连续 1 的个数
https://leetcode.cn/problems/max-consecutive-ones/description/
遍历数组,将1全部加起来,出现0就重置。
int findMaxConsecutiveOnes(int* nums, int numsSize) {int max = 0, cur = 0;for(int i = 0; i < numsSize; ++i) {cur = ++cur * nums[i];if(cur > max) max = cur;}return max;
}
这一个和上面是一样的思路,只是实现不同而已
int findMaxConsecutiveOnes(int* nums, int numsSize) {int max = 0, pre = 0;for(int i = 0; i < numsSize; ++i) {if(nums[i] == 0) {pre = 0;}else {pre += 1;if(pre > max) max = pre;}}return max;
}
第三题 2057. 值相等的最小索引
https://leetcode.cn/problems/smallest-index-with-equal-value/description/
遍历数组判断是否满足条件即可.
int smallestEqual(int* nums, int numsSize) {for(int i = 0; i < numsSize; ++i) {if(i % 10 == nums[i]) return i;}return -1;
}
第四题 27. 移除元素
https://leetcode.cn/problems/remove-element/
遍历数组,如果当前值和val
相等,则把当前值放到最后面同时size-1
,这样就访问不到了;
但是如果交换的最后一个值和当前值相等, 则需要继续判断;
int removeElement(int* nums, int numsSize, int val) {for(int i = 0; i < numsSize; ++i) {while(i < numsSize && nums[i] == val) {int temp = nums[i];nums[i] = nums[numsSize - 1];nums[numsSize - 1] = temp;--numsSize;}}return numsSize;
}
第五题 665. 非递减数列
https://leetcode.cn/problems/non-decreasing-array/description/
第一遍错误做法:
bool checkPossibility(int* nums, int numsSize) {int flag = 0;for(int i = 0; i < numsSize; ++i) {if(nums[i] > nums[i + 1]) {nums[i] -= nums[i + 1];flag++;}}if(flag > 1) {return false;}else {return true;}
}
需要多加写条件判断,还是太年轻了~
bool checkPossibility(int* nums, int numsSize) {int flag = 0;int pos = -1;for(int i = 0; i < numsSize - 1; ++i) {if(nums[i] > nums[i + 1]) {pos = i;flag++;}}if(flag >= 2) return false;if(flag == 0) return true;if(pos == 0 || nums[pos - 1] <= nums[pos + 1]) return true;if(pos == numsSize - 2 || nums[pos] <= nums[pos + 2]) return true;return false;
}