[leetcode-26-Remove Duplicates from Sorted Array]
Posted hellowOOOrld
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode-26-Remove Duplicates from Sorted Array]相关的知识,希望对你有一定的参考价值。
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.
思路:
使用两个下标分别来指示前边的一个元素和后边的一个元素,如果两个元素不相等,则两个下标均向后移动,
如果元素相等,则后一个向后移动,越过相等的元素,直到不相等为止,然后将该元素往前赋值。继续往后判断。
int removeDuplicates(vector<int>& nums) { if(nums.size()<=1)return nums.size(); int first =0; int second =1;//保存前后两个元素下标位置 while(second<nums.size()) { while(nums[first] == nums[second])second++; if(second<nums.size() && nums[first+1] != nums[second])nums[first+1] = nums[second]; if(second<nums.size()) first++; second++; } return first+1; }
学习别人后感觉写的好啰嗦。以下为参考别人的精简版本。
int removeDuplicates(int A[], int n) { if(n <= 1) return n; int cnt = 0; A[cnt++] = A[0]; for(int i=1; i<n; i++) { if(A[i] == A[i-1]) continue; else A[cnt++] = A[i]; } return cnt; }
参考:
https://www.nowcoder.com/profile/7671017/codeBookDetail?submissionId=10908027
以上是关于[leetcode-26-Remove Duplicates from Sorted Array]的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode]26. Remove Duplicates from Sorted Array
Leetcode 26. Remove Duplicates from Sorted Array
[leetcode-26-Remove Duplicates from Sorted Array]
Leetcode----26. Remove Duplicates from Sorted Array