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

Remove Element

时间:2015-02-03 00:33:05      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:

https://oj.leetcode.com/problems/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.

解题思路:

这题目巨坑爹,我看半天硬是没看懂什么意思。既然要求返回的只是length,那么直接减去==目标数值的数量不就可以了吗?可惜题目没说明的是,还要检查这个new length里面有没有这个目标value。我想也是这个题目含义比较ambiguous的地方。

public class Solution {
    public int removeElement(int[] A, int elem) {
        if(A.length == 0){
            return 0;
        }
        int left = 0;
        int right = A.length - 1;
        
        while(left <= right){
            if(A[left] == elem){
                int temp = A[left];
                A[left] = A[right];
                A[right] = temp;
                //这里直接A[left] = A[right]也可以,因为题目不要求后面的元素是啥
                right--;
            }else{
                left++;
            }
        }
        return right + 1;
    }
}

 另外还有其他两个解法,比我的代码更简单点。

public class Solution {
    public int removeElement(int[] A, int elem) {
        int count = 0;
        for(int i=0; i<A.length; i++){
            if(A[i] != elem){
                A[count] = A[i];
                count++;
            }
        }
        return count;
    }
}
public class Solution {
    public int removeElement(int[] A, int elem) {
        int length = A.length;
        int count = 0;
        for(int i = 0 ; i < length; i++){
            if(A[i] == elem){
                count++ ;
            }
            else{
                A[i-count] = A[i];
            }
        }
        return length-count;
    }
}

http://www.cnblogs.com/EdwardLiu/p/3703444.html

http://blog.hushlight.com/2015/01/remove-element/

Remove Element

标签:

原文地址:http://www.cnblogs.com/NickyYe/p/4268923.html

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