LeetCode第[26]題(Java):Remove Duplicates from Sorted Array 標籤:Array

來源:互聯網
上載者:User

標籤:rem   cat   迭代   case   png   tco   出現   重複   add   

題目難度: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 by modifying the input array in-place with O(1) extra memory.

翻譯:

給定一個排好序的數組後,重複資料刪除的元素,這樣每個元素只出現一次,並返回新的長度。

不要建立另一個數組分配額外的空間,只能通過修改原有數組,且空間複雜度為O(1)。

樣本:[1,1,2]——[1,2]  2

 

思路:一看見消除重複,就想到了Set,然後寫了代碼如下

1     public int removeDuplicates(int[] nums) {2         Set s = new HashSet();3         for (int i = 0; i < nums.length; i++) {4             s.add(nums[i]);5         }6         return s.size();7     }

但是答案說錯誤??

因為此題比較特殊,它不僅僅檢查最後的結果,而且檢查nums最後的值是否是期望的(只截取最後返回結果的大小)

然後我在後面加了個迭代器迴圈賦值,結果還是不對?

1         for (Iterator iterator = s.iterator(); iterator.hasNext();) {2             nums[i++] = (Integer) iterator.next();3         }

 

順序也要管?  好吧HashSet無序的,那就用TreeSet吧:

 1     public int removeDuplicates(int[] nums) { 2         Set<Integer> s = new TreeSet<Integer>(); 3         for (int i = 0; i < nums.length; i++) { 4             s.add(nums[i]); 5         } 6         int i = 0; 7         for (Iterator iterator = s.iterator(); iterator.hasNext();) { 8             nums[i++] = (Integer) iterator.next(); 9         }10         return s.size();11     }

 161 / 161 test cases passed. Status: Accepted Runtime: 24 ms   beats 5.31%

 

由於此處採用Set佔用了額外的空間,空間複雜度為O(N),雖然結果正確,但是不符合原題意圖,下面是參考答案。

 1 public int removeDuplicates(int[] nums) { 2     if (nums.length == 0) return 0; 3     int i = 0; 4     for (int j = 1; j < nums.length; j++) { 5         if (nums[j] != nums[i]) { 6             i++; 7             nums[i] = nums[j]; 8         } 9     }10     return i + 1;11 }

一開始有往這方面想,但是運行後發現邊界問題總是處理不了,就放棄了,

此處巧妙地採用了一個迴圈外的int做指標對原數組進行修改,同時迴圈內部從第二個開始與指標所指做比較,跳過重複的元素。

 

期間編譯錯誤:

1. if 後面的括弧內的判斷“==”寫成了“=”;

2. Set的toArray方法只能利用傳參toArray( new int[set.size()] ) 這樣才不會有轉型錯誤,但是這樣也只能轉為非基本類型(Integer而不能是nt),像轉為int數組只能利用迭代器進行迴圈賦值;

3. 忘記寫return。

LeetCode第[26]題(Java):Remove Duplicates from Sorted Array 標籤: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.