27. Remove Element

来源:互联网 发布:绵阳涪城广电网络热线 编辑:程序博客网 时间:2024/05/17 04:01

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

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

题意:去除数组中的所有val值,返回数组的新长度。

思路:注意对题意的理解,题意说不关心超出长度之后的数值,则思路是把所val值依次往后置换,然后返回置换后的索引+1。

class Solution {public:int removeElement(vector<int>& nums, int val) {int p, q;p = 0;q = nums.size() - 1;while (p <= q){if (nums[p] == val){nums[p] = nums[q];nums[q] = val;q--;}else{p++;}}return q + 1;}};



0 0
原创粉丝点击