2017.10.20 LeetCode Two Pointers 26. 27.

来源:互联网 发布:mysql索引失效 in or 编辑:程序博客网 时间:2024/04/27 13:51

26. Remove Duplicates from Sorted Array

Description

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.
题意: 给你一个数组,让你返回不同元素的个数 cnt,并且保证数组的前cnt个都是不同的
分析: 本题呢算是一种裸的Two Pointers 吧就是枚举两个端点,如果出现相同的话,就录下,不同的话就让当前的值移动到 (i-cnt)这来,自己模拟下就OK了

参考函数

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

27. Remove Element

Description

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

Do not allocate extra space for another array, you must do this in place with constant memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example:

Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.
题意: 将数组里的所有val值去掉,返回长度假设为len,那么前len个值都不等于val
分析: 和上一个题类似直接枚举即可

参考函数

class Solution {public:    int removeElement(vector<int>& nums, int val) {        int cnt = 0;        int len = nums.size();        for(int i = 0;i < len;i++) {            if(nums[i] == val) {                cnt++;            } else {                nums[i - cnt] = nums[i];            }        }        return len - cnt;    }};
原创粉丝点击