標籤:
【LeetCode】Remove Duplicates from Sorted Array 解題報告
標籤(空格分隔): LeetCode
[LeetCode]
https://leetcode.com/problems/remove-duplicates-from-sorted-array/
Total Accepted: 129010 Total Submissions: 384622 Difficulty: Easy
Question
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.
Ways
這個題一看就是雙指標。
基本一遍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;}
參考了這個之後我把My Code進行了最佳化:
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
竟然變慢了?
Date
2016 年 05月 8日
【LeetCode】Remove Duplicates from Sorted Array 解題報告