Leetcode[27]-Remove Element
2015-06-09 09:54
330 查看
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.
思路:遍历数组,如果数组对应的数等于给定的值,数组最后一位和当前位互换,然后将数组长度减一;否则,就执行i++;最后重置数组长度。
Code(c++):
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
思路:遍历数组,如果数组对应的数等于给定的值,数组最后一位和当前位互换,然后将数组长度减一;否则,就执行i++;最后重置数组长度。
Code(c++):
class Solution { public: void swap(int *a, int *b){ int temp = *a; *a = *b; *b = temp; } int removeElement(vector<int>& nums, int val) { int n = nums.size(); if(n == 0) return 0; int i = 0; while( i < n){ if(nums[i] == val) { swap(&nums[i],&nums[n-1]); n--; }else{ i++; } } nums.resize(n); return n; } };
相关文章推荐
- 【ZigZag Conversion】cpp
- Getting started with Yocto on Wandboard
- live555客户端连多路1080P视频流花屏问题
- 使用Windows Server 2012 建立ISCSI虚拟磁盘软存储
- C程序调用shell脚本共有三种方法
- 全局钩子详细解释
- 循环列表的Java实现,解决约瑟夫环问题
- 博客搭建步骤
- MySQL性能优化的21个最佳实践 和 mysql使用索引
- 大数据给嵌入式系统带来新的发展机遇
- ListView自动加载
- Building QT5 for IMX6(all)
- 循环列表的Java实现,解决约瑟夫环问题
- [emerg]: getpwnam(“nginx”) failed
- python 文件与目录的操作 未完善 需要重新学习
- leetcode-Symmetric Tree 对称树
- Linux学习之库函数方式文件编程
- 煤火车问题
- 微信JS接口汇总及使用详解(转)
- QT5安装(null)