0
点赞
收藏
分享

微信扫一扫

移出元素 Remove Element

正义的杰克船长 2022-12-02 阅读 110


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​

nums

Hint:

  1. Try two pointers.
  2. Did you use the property of "the order of elements can be changed"?
  3. What happens when the elements to remove are rare?

跟http://blog.csdn.net/gao1440156051/article/details/51743374  这题题类似



class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int len = nums.size();

int i = -1;
for (int j = 0; j < len; j++){
if (nums[j] != val){
swap(nums[++i], nums[j]);
}
}

return i + 1;
}
};




举报

相关推荐

0 条评论