[LeetCode]27.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.
【題意】
把數組中與給定值相同的元素刪除,在原數組上修改,返回值是最終元素個數。
【分析】
無
【代碼】
/********************************* * 日期:2014-01-19 * 作者:SJF0115 * 題號: Remove Element * 來源:https://oj.leetcode.com/problems/remove-element/ * 結果:AC * 來源:LeetCode * 總結: **********************************/ #include <iostream> #include <stdio.h> #include <vector> #include <set> #include <algorithm> using namespace std; class Solution { public: int removeElement(int A[], int n, int elem) { int index = 0; for(int i = 0;i < n;i++){ if(A[i] != elem){ A[index++] = A[i]; } } return index; } }; int main() { Solution solution; int result; int A[] = {3,2,5,4,2,6,3,2}; result = solution.removeElement(A,8,2); for(int i = 0;i < result;i++){ printf("%d ",A[i]); } printf("\nLength:%d\n",result); return 0; }
【代碼2】
class Solution { public: int removeElement(int A[], int n, int elem) { return distance(A,remove(A,A+n,elem)); } };
最後更新:2017-04-03 12:54:38