第四周Remove Duplicates from Sorted Array

Remove Duplicates from Sorted Array

Leetcode algorithms problem 26:Remove Duplicates from Sorted Array

  • 問題描述

    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.

  • 問題提示

    題目要求的即是找出不同的元素個數並放在最前面,返回該個數

  • 思路

    設一箇中間值,遍歷數組,將i與i的前一位比較,出現重複的數,中間值+1,否則把開始重複的第一個下標的值設爲i的值

代碼

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int numbers = 0;
        for(int i = 1; i < nums.size(); i++)
        {
            if(nums[i] == nums[i-1]) {
                numbers++;
            }
            else {
                nums[i-numbers] = nums[i];
            }
        }
        return nums.size() - numbers;
    }
};

時間複雜度: O(n)
空間複雜度: O(1)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章