[LeetCode][Java] Remove Duplicates from Sorted Array

來源:互聯網
上載者:User

標籤:leetcode   java   remove duplicates fr   

題目:

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.

題意:

給定一個排序數組,刪除數組中的重複元素使得數組中的每個元素都只出現一次,返回數組新的長度。

不要為新的數組分配空間,你必須使用常數空間。

比如:

給定輸入數組 nums = [1,1,2],

你所寫的函數需要返回長度2,數組中的兩個元素分別為1 and 2。數組中的超過這個長度的元素無關緊要。 

演算法分析:

利用雙指標

 * 前後兩個指標,前指標固定不動,後指標去搜尋
 * 直到後指標指到與前指標不同的元素上,這時統計到了第二個不同元素,i++;
 * 前指標重設到現在後指標的位置
 * 重複上述過程,能夠統計出不同的元素的總個數,而且原數組中的前i個元素即為這i個互為不同的元素

AC代碼:

/** * 前後兩個指標,前指標固定不動,後指標去搜尋 * 直到後指標指到與前指標不同的元素上,這時統計到了第二個不同元素,i++; * 前指標重設到現在後指標的位置 * 重複上述過程,能夠統計出不同的元素的總個數,而且原數組中的前i個元素即為這i個互為不同的元素 */ public class Solution {    public int removeDuplicates(int[] nums)     {if(nums.length==0) return 0;int startindex = 0;int endindex = 0;int i=0;    while(endindex<nums.length)    {    while(endindex<nums.length)    {    if(nums[startindex]==nums[endindex])     endindex++;    else    {    break;    }       }    nums[i]= nums[startindex];startindex=endindex;i++;    }return i;    }}


著作權聲明:本文為博主原創文章,轉載註明出處

[LeetCode][Java] 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.