LeetCode 26_Remove Duplicates from Sorted Array 移重
文章目录
题目
给定排好序的数组,计算不重复数的个数n,并将这n个数排在数组的前n位。不能使用辅助数组(额外空间)。
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.
https://leetcode.com/problems...
尝试
设两个指针,一个是新不重复数组的指针i,一个是原数组的指针gt。
gt走完判断即可。(说起来真是很容易。。。)
为什么写出来的如此累赘。。。
public int removeDuplicates(int[] nums) {
int gt=1;
if(nums.length<=1) return nums.length;
int i=1;
while(gt<nums.length){ //其实发现判断条件都是一个,如何精简?
while(gt<nums.length && nums[i-1]==nums[gt])
gt++;
if(gt<nums.length) {
nums[i]=nums[gt++];
i++;
}
}
return i;
}
借鉴
差距T-T
public int removeDuplicates(int[] A) {
if (A.length==0) return 0;
int i=0;
for (int gt=0; gt<A.length; gt++)
if (A[gt]!=A[i]) A[++i]=A[gt];
return ++i;
}

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论