[Leetcode] Remove Element

题目:

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)