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

Leetcode[27]-Remove Element

时间:2015-06-09 11:59:43      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:remove   element   leetcode   

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.


思路:遍历数组,如果数组对应的数等于给定的值,数组最后一位和当前位互换,然后将数组长度减一;否则,就执行i++;最后重置数组长度。

Code(c++):

class Solution {
public:

    void swap(int *a, int *b){
        int temp = *a;
        *a = *b;
        *b = temp;
    }
    int removeElement(vector<int>& nums, int val) {
        int n = nums.size();
        if(n == 0) return 0;
        int i = 0;
        while( i < n){
            if(nums[i] == val) {
                swap(&nums[i],&nums[n-1]);
                n--;
            }else{
                i++;
            }
        }
        nums.resize(n);
        return n;
    }
};

Leetcode[27]-Remove Element

标签:remove   element   leetcode   

原文地址:http://blog.csdn.net/dream_angel_z/article/details/46422765

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