【LeetCode】Remove Duplicates from Sorted Array 解題報告

來源:互聯網
上載者:User

標籤:

【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 解題報告

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.