LeetCode 26. Remove Duplicates from Sorted Array (Java)

题目:

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn’t matter what you leave beyond the returned length.

Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn’t matter what values are set beyond the returned length.

解答:

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

解析:

  1. 这道题的思路就是采用两个标记点 number 和 i ,number记录不重复元素的位置,i从number的下一个开始遍历数组,如果i位置的数字等于number位置的数字,说明该数字重复出现,不予处理;如果i位置的数字不等于number位置的数字,说明该数字没有重复,需要放到l的下一位置,并使number加1。

你可能感兴趣的:(LeetCode)