RemoveDuplicatesFromSortedArray [source code]

public class RemoveDuplicatesFromSortedArray {
static
/******************************************************************************/
public class Solution {
    public int removeDuplicates(int[] nums) {
        int n = nums.length;
        int tail = 0;
        for (int i = 1; i < n; i++) {
            if (nums[i] > nums[tail]) nums[++tail] = nums[i];
        }
        return tail + 1;
    }
}
/******************************************************************************/

    public static void main(String[] args) {
        RemoveDuplicatesFromSortedArray.Solution tester = new RemoveDuplicatesFromSortedArray.Solution();
        int[] input1 = {1,2,2,2,3,3,4};
        System.out.println(tester.removeDuplicates(input1));
        Printer.array (input1);
    }
}

仔细看题目, 这里不仅是要求 return 长度, 而且 nums 要能够被修改; 做题目的时候不要以为只要返回值满足要求题目就算做完了;

这个题目的思路其实是类似前面那个 move0的题目: 如果你死板的按照 stream 的思路去做, 最后可能免不了要用 shift, 速度就很慢; 就跟 move0那一题一样, 先想想你最后要的结果是怎么样的, 然后直接到这个结果;

总体来说这个题目还是很简单的, 最后的速度是13ms (77%), 中规中矩;


好像这个基本就是submission 最优解了; editorial最优解好像也是跟这个是一样的; discussion也没有什么更好的做法;


Problem Description

Given a sorted array, 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 in place with constant memory.

For example,
Given input array 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 new length.

Difficulty:Easy
Total Accepted:235.8K
Total Submissions:663.6K
Contributor: LeetCode
Companies
microsoft bloomberg facebook
Related Topics
array two pointers
Similar Questions
Remove Element

results matching ""

    No results matching ""