美文网首页
[LeetCode] 26. Remove Duplicates

[LeetCode] 26. Remove Duplicates

作者: hugo54 | 来源:发表于2020-01-06 15:25 被阅读0次
    class Solution {
        public int removeDuplicates(int[] nums) {
            if (nums.length <= 1) {
                return nums.length;
            }
            
            // p: the rightest endpoint pointer of a non-repeating subarray
            // q: the pointer to detect new non-repeating number
            int p = 0;
            int q = 1;
            
            // q keeps moving until it finds a non-repeating number or reaches to the end of the array.
            while (q < nums.length) {
                if (nums[p] != nums[q]) {
                    nums[p + 1] = nums[q];
                    p++;
                }
                q++;
            }
            
            // return the length of the non-repeating "array"
            return p + 1;
        }
    }
    

    相关文章

      网友评论

          本文标题:[LeetCode] 26. Remove Duplicates

          本文链接:https://www.haomeiwen.com/subject/rnjkactx.html