首頁 > Java > java教程 > 主體

LeetCode & Q26-從排序數組中刪除重複項-Easy

PHP中文网
發布: 2017-07-09 18:12:13
原創
1455 人瀏覽過

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 & Q26-從排序數組中刪除重複項-Easy的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板