码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Remove Element

时间:2014-10-26 00:20:26      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   sp   

题目:

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.

Tag:

Array; Two Pointers

体会:

我激动了,这道题和上一道Remove Duplicates from Sorted Array简直一模一样啊,就换了一个第6行有木有。详情可以参见上一篇文章

延伸:

我觉得这道题和刚才那个removeDuplicates完全可以延伸,就是问你,给你一个array, 怎么样知道他有多少个uniq的元素啊,把这些uniq的都找出来啊。那不是下sort一下,然后再把上一题的代码抄一遍嘛~

 1 class Solution {
 2 public:
 3     int removeElement(int A[], int n, int elem) {
 4         int pos = -1;
 5         for (int i = 0; i < n; i++) {
 6             if (A[i] != elem) {
 7                 pos++;
 8                 A[pos] = A[i];
 9             }
10         }
11         return pos + 1;
12     }
13 };

 

[Leetcode] Remove Element

标签:style   blog   http   color   io   os   ar   for   sp   

原文地址:http://www.cnblogs.com/stevencooks/p/4051090.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!