LeetCode 27. Remove Element
来源:互联网 发布:mac桌面双桌面用 编辑:程序博客网 时间:2024/06/06 13:15
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 by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
Example:
Given nums = [3,2,2,3], val = 3,Your function should return length = 2, with the first two elements of nums being 2.
移除数组中和给定值相同的元素,返回新数组的长度。不允许分配新的空间来制造新的数组,数组元素的顺序可以改变,新数组长度外的元素不需要理会。
这题还是用Two Pointers,一个指向数组当前尾元素(end),一个指向当前元素(i),若当前元素不等于给定值,那么i移到下一个元素;若当前元素等于给定值,就把尾元素的值赋给当前元素,并把end指针向前移一位。
int removeElement(vector<int>& nums, int val) { if (nums.size() == 0) return 0; int end = nums.size() - 1, i = 0; while (i <= end) { if (nums[i] == val) { nums[i] = nums[end]; --end; } else ++i; } return i; }
阅读全文
0 0
- [LeetCode]27.Remove Element
- LeetCode --- 27. Remove Element
- LeetCode 27.Remove Element
- [Leetcode] 27. Remove Element
- [Leetcode] 27.Remove Element
- 【leetcode】27. Remove Element
- 【leetcode】27. Remove Element
- Leetcode 27. Remove Element
- LeetCode 27. Remove Element
- 27. Remove Element LeetCode
- 【LeetCode】27. Remove Element
- leetcode 27. Remove Element
- leetcode 27. Remove Element
- [LeetCode]27. Remove Element
- LeetCode 27. Remove Element
- [leetcode] 27. Remove Element
- [leetcode] 27. Remove Element
- leetcode 27. Remove Element
- C++ primer 第五版 第四章练习答案
- LeetCode 26. Remove Duplicates from Sorted Array && 80. Remove Duplicates from Sorted Array II
- linux内核之进程的基本概念(进程,进程组,会话关系)
- 防止sql注入方法
- entity与vo的映射方法
- LeetCode 27. Remove Element
- 两圆的位置关系
- D3.js version4教程(1)
- 《ActiveMQ in Action》.pdf下载
- LeetCode 31. Next Permutation
- 图论三,四
- 关于STL的list容器总结
- ComputerGame---Sunday算法的应用
- DOS HOP原创舞蹈微电影-竹舞阁4