Leetcode刷題Java26. 刪除排序數組中的重複項

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

不要使用額外的數組空間,你必須在 原地 修改輸入數組 並在使用 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。

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

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

 class Solution {
        public int removeDuplicates(int[] nums) {

//            return removeDuplicatesI(nums);
            return removeDuplicatesII(nums);
        }

        //方法二:同樣定義index指針,比較前後元素
        private int removeDuplicatesII(int[] nums) {
            if (nums == null || nums.length == 0) return 0;
            int index = 1;
            for (int i = 1; i < nums.length; i++) {
                if (nums[i] != nums[i - 1]) {
                    nums[index++] = nums[i];
                }
            }
            return index;
        }

        //方法一:雙指針
        //定義指針index指向非重複元素
        private int removeDuplicatesI(int[] nums) {
            if (nums == null || nums.length == 0) return 0;
            int index = 0;
            for (int i = 1; i < nums.length; i++) {
                if (nums[i] != nums[index]) {
                    nums[++index] = nums[i];
                }
            }
            return index + 1;
        }
    }

 

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