首页 > 其他 > 详细

Leetcode[27]-Remove Element

时间:2015-06-09 11:58:52      阅读:169      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!