leetcode系列(42)Remove Duplicates from Sorted Array & Remove Element

来源:互联网 发布:加强网络舆情管理 编辑:程序博客网 时间:2024/06/05 05:57

RemoveDuplicates from Sorted Array

Given a sorted array, remove the duplicatesin place such that each element appear only once and return the newlength.

Donot allocate extra space for another array, you must do this in place withconstant memory.

Forexample,
Given input array nums = [1,1,2],

Yourfunction 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.

RemoveElement

Given an array and a value, remove allinstances of that value in place and return the new length.

The order of elements can be changed. Itdoesn't matter what you leave beyond the new length.

解答:这两个题目很相似,都是用一个idx只更新符合条件的元素,和qsort中的partition很像,直接上代码吧:

int removeDuplicates(vector<int>& nums) {        if (nums.size() == 0) {            return 0;        }        int i = 0;        for (int j = i + 1; j < nums.size(); ++j) {            if (nums[j] != nums[i]) {                ++i;                nums[i] = nums[j];            }        }        return i + 1;    }    int removeElement(vector<int>& nums, int val) {        int i = -1;        for (auto item : nums) {            if (item != val) {                ++i;                nums[i] = item;            }        }        return i + 1;    }


0 0