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-Remove Duplicates from Sorted Array-Easy的详细内容。更多信息请关注PHP中文网其他相关文章!