26.Remove Deplicates from Sorted Array
Posted dreamafar
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了26.Remove Deplicates from Sorted Array相关的知识,希望对你有一定的参考价值。
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.
算法:
因为数组已经有序,我们可以维持两个指针i 和 j, 只要nums[i] == nums[j], 就增加j 来跳出循环。
当遇到nums[j] != nums[i], 查重循环结束, 我们必须把nums[j] 的值复制给nums[i+1】,i 然后增加。
重复这一过程直到j 到达数组尾部。
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; }
以上是关于26.Remove Deplicates from Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章
26Remove Duplicates from Sorted Array
26. Remove Duplicates from Sorted Array
#26 Remove Duplicates from Sorted Array
26. Remove Duplicates from Sorted Arrayeasy