题目:
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array nums =[1,1,2]
, Your function should return length = 2
, with the first two elements of nums being 1
and 2
respectively. It doesn't matter what you leave beyond the new length. (Easy)
分析:
这道题和下一个都是简单的双重指针倒腾数组元素的题。
开始做的时候居然一直想swap,导致代码有点复杂,而且有一些情况开始没想到。
当时去摩根面试的时候第一题就是这个,想想自己当时真是水的不行,怪不得被刷了...
代码1:(swap的,要多一个cur记录是否重复,因为交换后会出现没法跟前一个比较。 不知道为什么脑子秀逗一直要swap...)
1 class Solution { 2 public: 3 int removeDuplicates(vector & nums) { 4 if (nums.size() == 0) { 5 return 0; 6 } 7 int p1 = 1, p2 = 1; 8 int cur = nums[0]; 9 while (p1 != nums.size()) {10 if (nums[p1] != cur) {11 cur = nums[p1];12 if (p1 != p2) {13 swap(nums[p1], nums[p2]);14 }15 p2++;16 }17 p1++;18 }19 return p2;20 }21 };
代码2: (不要交换,就是两个指针,有一个维护所有不重复的元素,发现就拷过去,这多简单....)
1 class Solution { 2 public: 3 int removeDuplicates(vector & nums) { 4 if (nums.size() == 0) { 5 return 0; 6 } 7 int p1 = 1, p2 = 1; 8 while (p1 != nums.size()) { 9 if (nums[p1] != nums[p1 - 1]) {10 nums[p2] = nums[p1];11 p2++;12 }13 p1++;14 }15 return p2;16 }17 };
代码3: (写成for循环虽然双重指针没那么明显,但是代码好看一些,以后还是这么写)
1 class Solution { 2 public: 3 int removeDuplicates(vector & nums) { 4 if (nums.size() == 0) { 5 return 0; 6 } 7 int p = 1; 8 for (int i = 1; i < nums.size(); ++i) { 9 if (nums[i] != nums[i - 1]) {10 nums[p] = nums[i];11 p++;12 }13 }14 return p;15 }16 };