【LeetCode-面試演算法經典-Java實現】【026-Remove Duplicates from Sorted Array(刪除排序數組中的重複元素)】,removeduplicates

來源:互聯網
上載者:User

【LeetCode-面試演算法經典-Java實現】【026-Remove Duplicates from Sorted Array(刪除排序數組中的重複元素)】,removeduplicates
【026-Remove Duplicates from Sorted Array(刪除排序數組中的重複元素)】【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】原題

  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.

題目大意

  給定一個排序的數組,將數組中的重複元素去掉,相同的只保留一個,並且返回數組新的元素個數,不要建立一個新的數組來儲存結果。在常量時間內解決這個問題

解題思路

  從第二個元素開始處理,記為當前處理的元素,如果當前元素與他的前一個元素相同就刪除這個元素,如果不同就將它移動到正確的位置,返回最後數組元素人個數。

代碼實現

演算法實作類別

public class Solution {    public int removeDuplicates(int[] A) {        if (A.length == 0) {            return 0;        }        int index = 0;//[0,index]只記錄數組中出現的按從小到大的唯一一個數,已經排好序了        int next = 1;        // 演算法思想:找index之後的比A[index]大的數,如是找到就移動到A[index+1]處,        // index移動到下一個位置,next移動到下一個位置,再找比A[index]大的數        while (next < A.length) {            while (next < A.length && A[index] == A[next] ) { // 找不等於數組中最                next++;            }            if (next < A.length) {                index++;                A[index] = A[next];                next++;            }        }        return index + 1;    }    private void swap(int[] a, int x, int y) {        int tmp = a[x];        a[x] = a[y];        a[y] = tmp;    }}
評測結果

  點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。

特別說明歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47034985】

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.