LeetCode 27:Remove Element
2015-11-30 22:16
579 查看
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.
方法一:
方法二:
//利用一个变量index和数组的下标i同时从数组起始位置遍历,当nums[i]!=val时,将nums[i]赋值给nums[index],
//若nums[i]=val,则不进行任何操作,跳过往后面继续遍历
class Solution{
public:
int removeElement(vector<int>& nums, int val){
int n = nums.size();
int index = 0;
for (int i = 0; i < n; ++i){
if (nums[i] != val){
nums[index++] = nums[i];
}
}
return index;
}
};
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
方法一:
#include<iostream> #include<vector> #include<stack> using namespace std; //利用栈的方法 class Solution{ public: int removeElement(vector<int>& nums, int val){ stack<int> stack1; int n = nums.size(); if (n == 0) return 0; for (int i = 0; i < n; i++){ if (nums[i] != val){ stack1.push(nums[i]); } else{ continue; } } int n2 = stack1.size(); for (int j = n2-1; j >=0; j--){ nums[j] = stack1.top(); stack1.pop(); } return n2; } }; int main() { Solution sol; vector<int> nums1 = { 1, 2, 3,3, 4, 5 }; int n1 = sol.removeElement(nums1,3); cout << n1 << endl; for (int i = 0; i < n1; ++i){ cout << nums1[i] << ','; } system("pause"); return 0; }
方法二:
//利用一个变量index和数组的下标i同时从数组起始位置遍历,当nums[i]!=val时,将nums[i]赋值给nums[index],
//若nums[i]=val,则不进行任何操作,跳过往后面继续遍历
class Solution{
public:
int removeElement(vector<int>& nums, int val){
int n = nums.size();
int index = 0;
for (int i = 0; i < n; ++i){
if (nums[i] != val){
nums[index++] = nums[i];
}
}
return index;
}
};
相关文章推荐
- 实现一段字符串中部分内容字体颜色大小变化
- Julia: h5write ,h5read 与ASCIIString、Float64及效率比较
- leetcode power of two
- [转]F5负载均衡环境下某应用故障分析案例
- 查询进程打开的文件[转]
- Dialog使用总结
- 5.x控件:Toolbar、TabLayout、CoordinatorLayout
- 汇编中定义数组与变量
- 对用户定义的完整性的认识
- shell修改文件名
- fedora 20 yum出错
- 实验五
- 计算机经典书籍
- ios 面试题(1)
- 学习maven的各种问题
- Windows下安装Mysql
- jquery操作dom
- Qt 创建菜单
- 链接GitHub上传和修改代码并打tag
- Eclipse去除jquery引入错误