アルゴリズム:ソートされた配列から重複データを削除する26.ソートされた配列から重複を削除する

:LeetCodeの完全なコレクションについては、を参照してくださいLeetCode Githubのコレクション

トピック

26.並べ替え
られた配列から重複を削除する並べ替えられた配列numを指定して、各要素が1回だけ表示され、新しい長さを返すように、重複をインプレースで削除します。

別の配列に余分なスペースを割り当てないでください。O(1)の余分なメモリを使用して入力配列をインプレースで変更することによってこれを行う必要があります。

明確化:

戻り値が整数であるのに、答えが配列である理由がわかりませんか?

入力配列は参照によって渡されることに注意してください。これは、入力配列への変更が呼び出し元にも認識されることを意味します。

内部的には、これについて考えることができます。

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    
    
    print(nums[i]);
}

例1:

Input: nums = [1,1,2]
Output: 2, nums = [1,2]
Explanation: 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 returned length.

例2:

Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4]
Explanation: Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. It doesn't matter what values are set beyond the returned length.

制約:

0 <= nums.length <= 3 * 104
-104 <= nums[i] <= 104
nums is sorted in ascending order.

2つのポインタで解く

  1. 境界を決定し、配列が空の場合は0を返します。
  2. 前の最後の番号と、重複していない現在の位置インデックスを記録します。
  3. 前の番号と等しくないことがわかるまで配列をトラバースしてから、現在の番号を次のインデックスに割り当て、preを現在の番号に置き換えます。
class Solution {
    
    
    public int removeDuplicates(int[] nums) {
    
    
        // check edge
        if (nums == null || nums.length == 0) {
    
    
            return 0;
        }
        int pre = nums[0];
        int index = 1;
        for (int k = 1; k < nums.length; k++) {
    
    
            if (nums[k] != pre) {
    
    
                nums[index] = nums[k];
                index++;
                pre = nums[k];
            }
        }
        
        return index;
    }
}

おすすめ

転載: blog.csdn.net/zgpeace/article/details/113695763