题意:在有序数组中删除重复元素
https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
解法:双指针,i记录答案,j遇到重复的值就往后跳过
class Solution {
public:int removeDuplicates(vector<int>& nums) {int i = 0;for(int j = 0; j < nums.size(); j++) {while (j > 0 && j < nums.size() && nums[j] == nums[j-1]) {j++;} if(j < nums.size()) {nums[i++] = nums[j];}}return i;}
};
解法二:双指针,但是判断的条件是略有不同,是判断j指向元素和i指向元素是否重复,代码更为简洁
class Solution {public:int removeDuplicates(vector<int>& a) {int i = 0;for (int j = 0; j < a.size(); j++)if (!i || a[j] != a[i - 1]) a[i++] = a[j];return i;}
};
时间复杂度 O ( n ) O(n) O(n)
空间复杂度 O ( 1 ) O(1) O(1)