2018-04-12

26. Remove Duplicates from Sorted Array

  • 用两个指针 two pointers.
  • Time Complexity = O(n): each of i and j traverses at most n steps.

  • Space Complexity = O(1)

class Solution {    // brute force 
    public int removeDuplicates(int[] nums) {
        
        
        
        
        Set set = new HashSet<>();
        int len = nums.length;
        int uniqueSize = 0;
        for (int i = 0; i < len; i++) {
            if (!set.contains(nums[i])) {
                set.add(nums[i]);
                uniqueSize ++;
            }
        }
        return uniqueSize;
    }
}

// But in this way, we utilized new space HashSet.
// How to take out an elements, while move all other elements up. 
// Say, Delete. 

// Also, consider the CORNER CASE!!!

Solution: Approach #1 (Two Pointers) [Accepted]

  • 理解:
  1. Sorted array:相同的字符一定是连在一起的;新check的数字也 一定 只可能和其前一个数字相同。
  2. 新返回的数组,不会比原数组size大。
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;
}

### 27. Remove Element

  • 发现自己总是不记得claim variable...
    int len = nums.length;
class Solution {
    public int removeElement(int[] nums, int val) {
        int len = nums.length;
        int i = 0, j = 0;
        for (j = 0; j < len; j++) {
            if (nums[j] != val){
                nums[i] =  nums[j];
                i++ ; 
            }
        }
        return i; // Caution: where you do i ++
    }
}

Solution:

public int removeElement(int[] nums, int val) {
    int i = 0;
    for (int j = 0; j < nums.length; j++) {
        if (nums[j] != val) {
            nums[i] = nums[j];
            i++;
        }
    }
    return i;
}

你可能感兴趣的:(2018-04-12)