程序媛詹妮弗
终身学习

Two Pointers(指针i扫旧, 指针start上新)模板:

*用指针start帮助生成新数组。指针start指向下一个即将生成的,符合条件的元素的位置。 // save a position for next valid item 
*用指针i扫给定数组A
*若扫到的A[i]符合新数组对元素的要求,令A[start]=A[i] 

Two Pointers(指针i扫旧, 指针start上新)高频题:

[leetcode]26. Remove Duplicates from Sorted Array有序数组去重(单个元素只出现一次)

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

[leetcode]80. Remove Duplicates from Sorted Array II有序数组去重(单个元素可出现两次)

class Solution {
    public int removeDuplicates(int[] nums) {
        // corner case
        if(nums.length == 0 || nums == null) return 0;
        int start = 2;
        for(int i = 2; i < nums.length; i++){
            if(nums[i] != nums[start-2]){
                nums[start] = nums[i];
                start++;
            }
        }
      return start;
    }
}

[leetcode]283. Move Zeroes移零

class Solution {
    public void moveZeroes(int[] nums) {
        int start = 0;
        for(int i = 0; i < nums.length; i++){
            if(nums[i] != 0){
                nums[start] = nums[i];
                start++; 
            }   
        }       
        for(int i = start; i< nums.length; i++){
            nums[i] = 0;
        }
    }
}

[leetcode]27. Remove Element删除元素

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

  

posted on 2020-12-29 05:58  程序媛詹妮弗  阅读(142)  评论(0编辑  收藏  举报