leetcode之刪除排序數組中的重複項

問題描述:

給定一個排序數組,你需要在 原地 刪除重複出現的元素,使得每個元素只出現一次,返回移除後數組的新長度。

不要使用額外的數組空間,你必須在 原地 修改輸入數組 並在使用 O(1) 額外空間的條件下完成。

示例1:

          輸入: nums = [1,1,2]

          輸出:   數應該返回新的長度2,並且原數組nums的前兩個元素被修改爲1,2.

          說明:你不需要考慮數組中超出新長度後面的元素。

示例2:

          輸入: nums = [0,0,1,1,1,2,2,3,3,4]

          輸出:函數應該返回新的長度5,並且原數組nums的前五個元素被修改爲0,1,2,3,4

解法一:使用雙指針

class Solution {
    public int removeDuplicates(int[] nums) {
       int len = nums.length;
       int left = 0;
       int right = 1;
       while(right < len){
           if(right - left != 1 && nums[left] != nums[right]){
               int end = right;
                for(int i = left+1 ; end < len;i++){
                        nums[i] = nums[end++];
                }
                len = len - (right - left) + 1;
                left = left + 1;
                right = left + 1;
           }
           if(nums[left] != nums[right]){
               left++;
               right++;
           }else{
               right++;
               if(right == len && nums[left] == nums[right - 1]){ //考慮到數組最後幾位相同的特殊情況
                   len = len - (right - left) + 1;
               }
           }
       }
       return len;
    }
}

官方代碼:

class Solution{
    public int removeDuplicates(int[] nums) {
        if (nums.length == 0) return 0;
        int i = 0;
        for (int j = 1; j < nums.length; j++) {
            if (nums[j] != nums[i]) {
                i++;
                nums[i] = nums[j];
            }
        }
        return i + 1;
    }
}

----------------------------------------------------------------------------------------------------------------------------------------------------------------------
作者:LeetCode
鏈接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/solution/shan-chu-pai-xu-shu-zu-zhong-de-zhong-fu-xiang-by-/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章