您的位置:首页 > 运维架构

Leetcode 27. Remove Element

2017-01-26 10:25 459 查看
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.

s思路:

1. 思路和26.Remove Duplicates from Sorted Array一样。仍然是two pointer.

2. 区别就是,两个指针都从最右边往左移动,用右指针到array的最右端之间的subarray来存放等于val的值。



//two pointer
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
//
int n=nums.size();
int right=n-1;
for(int left=n-1;left>=0;left--){
if(nums[left]==val){
nums[left]=nums[right];
nums[right]=val;
right--;
}
}
return right+1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode twopointer