283. 移动零
- 283. 移动零
- 思路:代码中注释阐述
- 时间:O(n);空间:O(1)
class Solution {
public:void moveZeroes(vector<int>& nums) {int p = 0, q = 0;int size = nums.size();while(q < size){if(nums[q] != 0){int temp = nums[p];nums[p] = nums[q];nums[q] = temp;++p;}++q;}}
};
88. 合并两个有序数组
- 88. 合并两个有序数组
- 思路:如注释
- 时间:O(m + n);空间:O(1)
class Solution {
public:void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {int p = m - 1, q = n - 1;int tail = m + n - 1; while(p >= 0 && q >= 0){if(nums1[p] > nums2[q]){nums1[tail--] = nums1[p--];} else {nums1[tail--] = nums2[q--];}}while(q >= 0){nums1[tail--] = nums2[q--];}}
};