Remove Element -LeetCode

来源:互联网 发布:2016年破获的网络诈骗 编辑:程序博客网 时间:2024/06/05 17:58
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.
 
这道题在LeetCode上属于Easy类,本来没什么好说,但我水平低,仍然从这道简单题里长了见识。
此题初看之下,既要in place,又要O(n)复杂度,似乎比较难的样子,但请看代码:
int removeElement(vector<int>& nums, int val) {
                int p = 0;
                for(int i = 0; i < nums.size(); ++i)        {            if(nums[i] != val)            {                nums[p++] = nums[i];            }        }
                return p;    }
十分简洁!代码比较简单,就不解释了。Leetcode上有些题目是考察算法或者说技巧的,想到了实现起来就很简单,想不到可能就觉得这道题难,比如Single Number;还有一部分题算法不难,重在实现,比如字符串相关的题目。
 
这题的思想也可以用到其他的题目如Remove Duplicate等,这样就可以用线性时间删除序列里的重复元素。
0 0
原创粉丝点击