Leetcode 26 Remove Duplicates from Sorted Array

HowieLee59發表於2018-10-23

Given a sorted array, remove the duplicates in place such that each element appear only onceand 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 A =[1,1,2],

Your function should return length =2, and A is now[1,2].

1)使用set進行一重篩選後將陣列中元素進行修改

class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums == null || nums.length == 0){
            return 0;
        }
        int count = 0;
        Set<Integer> set = new HashSet<>();
        for(int i = 0 ; i  < nums.length ; i++){
            if(!set.contains(nums[i])){
                nums[count++] = nums[i];
                set.add(nums[i]);
            }
        }
        return count;
    }
}

2)使用雙指標進行標記,比較奇妙(100%)

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

 

相關文章