Remove Element

来源:互联网 发布:单晶片编程 编辑:程序博客网 时间:2024/05/30 22:58

Remove Element

 Total Accepted: 2651 Total Submissions: 7854My Submissions

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.

题意:给一个数组和一个目标数,要求把数组中的所有与目标数相同的元素移除,同时返回删除后数组的长度。

         但要注意,新的数组必须包含原来数组中除了目标数以外的所有数。

思路:用一个start下标记录当前新数组的长度,遍历原数组,遇到与目标数不同的数就把它赋值到新数组中,start往后移动。

class Solution {public:    int removeElement(int A[], int n, int elem) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.                int start = 0;        for(int i=0; i<n; i++){            if(A[i] != elem){                A[start++] = A[i];            }        }        return start;    }};





原创粉丝点击