# 0026. Remove Duplicates from Sorted Array ###### tags: `Leetcode` `双指针` Link: https://leetcode.com/problems/remove-duplicates-from-sorted-array/ ## 思路 这道题有规定不能新建一个阵列来存结果,因此采用双指针法,在原阵列上改。一个指向回圈跑到的位置,另一个则指向改到的位置。 ## Code ```c= class Solution { public: int removeDuplicates(vector<int>& nums) { if(nums.size() == 0){ return 0; } int j = 0; for(int i = 1;i < nums.size();i++){ if(nums[j]!=nums[i]){ j++; nums[j] = nums[i]; } } return j+1; } }; ``` ## 注意 只会检查array里面前m个元素(m为return的值),一开始我还在想要不要把后面的都删掉(尴尬) ## Code in Java ### 初级版 #### 我是咋想出来这么绕的算法的。。。 ```java class Solution { public int removeDuplicates(int[] nums) { int len0 = nums.length; if (len0 < 2) return len0; int len, i; len = 0; i = 0; while(i < len0){ int j = i + 1; while ( j < len0 && nums[i] == nums[j]){ j++; } i = j; if (j < len0){ nums[++len] = nums[j]; } } return len + 1; } } ``` ### 进阶版 ```java class Solution { public int removeDuplicates(int[] nums) { int j = 0; for (int i = 1; i < nums.length; i++){ if (nums[i] != nums[j]){ nums[++j] = nums[i]; } } return ++j; } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up