【LeetCode-面接アルゴリズムクラシック-Java実装】【026-Remove Duplicates from Sorted Array(ソート配列の重複要素を削除)】


【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.
テーマの大意
ソートされた配列を指定し、配列内の重複要素を削除し、同じものを1つだけ保持し、結果を保存するために新しい配列を作成しないで、配列の新しい要素の個数を返します.この問題を一定時間で解決する
問題を解く構想.
2番目の要素から処理を開始し、現在処理されている要素として記録し、現在の要素が前の要素と同じであれば削除し、異なる場合は正しい位置に移動し、最後の配列要素の人数を返します.
コード実装
アルゴリズム実装クラス
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】