标签:
标签(空格分隔): LeetCode
[LeetCode]
https://leetcode.com/problems/remove-duplicates-from-sorted-array/
Total Accepted: 129010 Total Submissions: 384622 Difficulty: Easy
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.
这个题一看就是双指针。
基本一遍AC。
需要注意的是count初始值是1,这样做的意义在于底下如果直接就返回的话也不会使数组内容为空。
第一次提交如下,后面有优化。
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length<=1) return nums.length;
int head=0;
int next=1;
int count=1;
while(next < nums.length){
while(nums[head] == nums[next]){
next++;
if(next>=nums.length) return count;
}
nums[head+1]=nums[next];
head++;
next++;
count++;
}
return count;
}
}
AC:1ms
下面这个是LeetCode的官方解答。刚开始不是很懂,但是看一下明白了,说的是只要不等就把头指针的下一个元素换成尾指针指向的元素。如果相等的话,尾指针继续往后走。
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;
}
参考了这个之后我把我的代码进行了优化:
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length<=1) return nums.length;
int head=0;
int next=1;
while(next < nums.length){
if(nums[head] == nums[next]){
next++;
continue;
}
nums[head+1]=nums[next];
head++;
next++;
}
return head+1;
}
}
AC:2ms
竟然变慢了?
2016 年 05月 8日
【LeetCode】Remove Duplicates from Sorted Array 解题报告
标签:
原文地址:http://blog.csdn.net/fuxuemingzhu/article/details/51346776