Descriptions:
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 being1
and2
respectively. It doesn 't matter what you leave beyond the new length.
我寫的一直有問題...用了HashSet集合,沒有研究過這個類型,[1,1,2]輸出結果一直是[1,1]
(在小本上記下,要研究HashSet)
<code class="sourceCode java"><span class="kw">import java.util.HashSet;</span> <span class="kw">import java.util.Set;</span> <span class="kw">public</span> <span class="kw">class</span> Solution { <span class="kw">public</span> <span class="dt">static</span> <span class="dt">int</span> <span class="fu">removeDuplicates</span>(<span class="dt">int</span>[] nums) { Set<Integer> tempSet = <span class="kw">new</span> HashSet<>(); <span class="kw">for</span>(<span class="dt">int</span> i = <span class="dv">0</span>; i < nums.<span class="fu">length</span>; i++) { Integer wrap = Integer.<span class="fu">valueOf</span>(nums[i]); tempSet.<span class="fu">add</span>(wrap); } <span class="kw">return</span> tempSet.<span class="fu">size</span>(); } }</code>
下面是優秀答案
Solutions:
<code class="sourceCode java"><span class="kw">public</span> <span class="kw">class</span> Solution { <span class="kw">public</span> <span class="dt">static</span> <span class="dt">int</span> <span class="fu">removeDuplicates</span>(<span class="dt">int</span>[] nums) { <span class="dt">int</span> j = <span class="dv">0</span>; <span class="kw">for</span>(<span class="dt">int</span> i = <span class="dv">0</span>; i < nums.<span class="fu">length</span>; i++) { <span class="kw">if</span>(nums[i] != nums[j]) { nums[++j] = nums[i]; } } <span class="kw">return</span> ++j; } }</code>
有兩個點要注意:
j++
和++j
的區別,此處用法很巧妙,也很有必要! 以上是LeetCode & Q26-從排序數組中刪除重複項-Easy的詳細內容。更多資訊請關注PHP中文網其他相關文章!