首页 >Java >java教程 >LeetCode & Q26-Remove Duplicates from Sorted Array-Easy

LeetCode & Q26-Remove Duplicates from Sorted Array-Easy

PHP中文网
PHP中文网原创
2017-07-09 18:12:131473浏览

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 being 1 and 2 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>

有两个点需要注意:

  1. 因为重复的可能有多个,所以不能以相等来做判定条件
  2. 注意j++++j的区别,此处用法很巧妙,也很必要!

以上是LeetCode &amp; Q26-Remove Duplicates from Sorted Array-Easy的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn