26. Remove Duplicates from Sorted Array

【题目】

Given a sorted arraynums, 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 by modifying the input array in-place with O(1) extra memory.

給定一個排序數組,你需要在原地刪除重複出現的元素,使得每個元素只出現一次,返回移除後數組的新長度。

不要使用額外的數組空間,你必須在原地修改輸入數組並使用O(1)額外空間的條件下完成。

Example:

Given nums = [0,0,1,1,1,2,2,3,3,4],

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.

【思路】

做法和Remove Element一樣,因為不需要在意後續Array的長度,

所以就直接如果不重複的話,調整Array位置就好。

【解法】

☆JAVA

class Solution {
    public int removeDuplicates(int[] nums) {
        int answer = 0;
        int nowCheck = 0;                                //目前檢核值
        if(null != nums && nums.length>0){
            for(int i = 0 ; i<nums.length ; i++){
                if(nowCheck!=nums[i] || i==0 ){          //如檢核值不等於陣列值,表示為非重複值,且第一次一定會進來
                    nowCheck = nums[i];                  //替換檢核值
                    nums[answer] = nowCheck;
                    answer++;
                }
            }
        }
        return answer;
    }
}

☆Python

class Solution:
def removeDuplicates(self, nums):
    answer = 0;
    checkNumber = 0;                                    //目前檢核值
    if nums:
        for i in range(len(nums)):
            if(checkNumber != nums[i] or i == 0):       //如檢核值不等於陣列值,表示為非重複值,且第一次一定會進來
                checkNumber = nums[i];                  //替換檢核值
                nums[answer] = checkNumber;
                answer += 1;
    return answer;

results matching ""

    No results matching ""