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

lintcode-easy-Remove Element

时间:2016-03-06 11:20:57      阅读:195      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!