首页 > 其他 > 详细

lintcode-easy-Remove Element

时间:2016-03-06 11:18:40      阅读:154      评论:0      收藏:0      [点我收藏+]

Given an array and a value, remove all occurrences of that value in place and return the new length.

The order of elements can be changed, and the elements after the new length don‘t matter.

 

Given an array [0,4,4,0,0,2,4,4]value=4

return 4 and front four elements of the array is [0,0,0,2]

 

可能是写的不够好,left最后对应的数可能是要删除的数,也可能不是,要检查一下。这种方法会比第二种方法快一点,因为是通过两个指针交换实现的。

第二种方法代码比较清晰,不需要最后检查,但是会稍微慢一点。

public class Solution {
    /** 
     *@param A: A list of integers
     *@param elem: An integer
     *@return: The new length after remove
     */
    public int removeElement(int[] A, int elem) {
        // write your code here
        
        if(A == null)
            return 0;
        if(A.length == 0)
            return 0;
        
        int left = 0;
        int right = A.length - 1;
        
        while(true){
            while(left < right && A[left] != elem)
                left++;
            while(left < right && A[right] == elem)
                right--;
            
            if(left == right)
                break;
            
            swap(A, left, right);
        }
        
        if(A[left] == elem)
            return left;
        else
            return left + 1;
    }
    
    public void swap(int[] A, int i, int j){
        int temp = A[i];
        A[i] = A[j];
        A[j] = temp;
        return;
    }
}
public class Solution {
    /** 
     *@param A: A list of integers
     *@param elem: An integer
     *@return: The new length after remove
     */
    public int removeElement(int[] A, int elem) {
        // write your code here
        if(A == null || A.length == 0)
            return 0;
        
        int tail = 0;
        for(int i = 0; i < A.length; i++){
            if(A[i] != elem){
                A[tail++] = A[i];
            }
        }
        
        return tail;
    }
}

 

lintcode-easy-Remove Element

原文:http://www.cnblogs.com/goblinengineer/p/5246599.html

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