27. Remove Element 难度:easy
2017-01-07 12:01
260 查看
题目:
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 =
Your function should return length = 2, with the first two elements of nums being 2.
思路:
对数组进行一次遍历,删除与给定值相等的关键字,返回新长度即可。
程序:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int i = 0 , k = 0;
while (i < nums.size())
{
if (nums[i] != val)
nums[k++] = nums[i];
i++;
}
return k;
}
};
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.
思路:
对数组进行一次遍历,删除与给定值相等的关键字,返回新长度即可。
程序:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int i = 0 , k = 0;
while (i < nums.size())
{
if (nums[i] != val)
nums[k++] = nums[i];
i++;
}
return k;
}
};
相关文章推荐
- 389. Find the Difference 难度:easy
- LeetCode[169. Majority Elemen] 难度[easy]
- 283. Move Zeroes 难度:easy
- 118. Pascal's Triangle 难度:easy
- 404. Sum of Left Leaves 难度:easy
- LeetCode [292. Nim Game] 难度[easy]
- LeetCode [448. Find All Numbers Disappeared in an Array] 难度[easy]
- 第二次做leetcode中的难度为easy的题-258
- 453. Minimum Moves to Equal Array Elements 难度:easy
- 447. Number of Boomerangs 难度:easy
- 461. Hamming Distance 难度:easy
- Leetcode 刷题 Binary Search Easy难度经验总结
- 1.Two Sum 难度:easy
- 169. Majority Element 难度:Easy 类别:分治
- LeetCode[136. Single Number] 难度[easy]
- 383. Ransom Note 难度:easy
- 318. Maximum Product of Word Lengths 难度:easy
- [leetcode]题解+经验总结 自己做法+评论区mostvotes汇总 (只包含部分easy难度)
- 448. Find All Numbers Disappeared in an Array 难度:easy
- 算法设计与分析(14)-- Valid Parentheses(难度:Easy)