27. Remove Element
来源:互联网 发布:电脑怎么识别不了网络 编辑:程序博客网 时间:2024/06/02 19:19
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.
方法一、使用vector自带的函数erase (不好的办法)
int removeElement(vector<int>& nums, int val) { int len = nums.size(); if(len<=0) { return len; } vector<int>::iterator it; for(it = nums.begin(); it != nums.end(); ) { //cout<<*it<<endl; if(*it == val)//注意:erase函数返回的是删除元素的后一个位置,自动隐含加一的操作 { nums.erase(it); } else { it++; } } return nums.size(); // return 0; }
方法二、简洁的办法
int removeElement(vector<int>& nums, int val) { int count = 0; for(int i = 0; i < nums.size(); i++) { if(nums[i] == val) count++; else nums[i-count] = nums[i]; } return nums.size() - count; }
0 0
- [LeetCode]27.Remove Element
- LeetCode --- 27. Remove Element
- LeetCode 27.Remove Element
- [Leetcode] 27. Remove Element
- 27.Remove Element
- [Leetcode] 27.Remove Element
- 27. Remove Element
- 27. Remove Element
- 【leetcode】27. Remove Element
- 【leetcode】27. Remove Element
- 27. Remove Element
- 27. Remove Element
- 27. Remove Element
- Leetcode 27. Remove Element
- 27. Remove Element
- LeetCode 27. Remove Element
- 27. Remove Element LeetCode
- 27. Remove Element
- 牛顿迭代法
- RecyclerView.OnScrollListener 滑动 逻辑需要在修改
- 关于android手机system/build.prop的浅析
- Python3爬虫从入门到自残(二):HTML及其解析
- Spark配置参数
- 27. Remove Element
- PAT 乙级 1042. 字符统计(20) Java版
- iOS检测设备摄像头、指南针、录音、陀螺仪状态
- 简述unity中material.color及Color.Lerp线性插值的用法
- HDU
- 39. Combination Sum
- 内存对齐宏ALIGN
- java取整和java四舍五入方法
- 隐马尔可夫模型(四)——隐马尔可夫模型的评估问题(后向算法)