现在的位置: 首页 > 综合 > 正文

Remove Element

2014年10月04日 ⁄ 综合 ⁄ 共 866字 ⁄ 字号 评论关闭

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和j指针,i指向数组的头部,j指向尾部,从头开始搜索,找到第一个等于elem值得位置,与尾部第一个不等于elem的第一个进行交换,交换完之后,low++,high--;

public class Solution {
    public int removeElement(int[] A, int elem) {
        int low = 0;
        int temp;
        int count = 0;
        int high = A.length - 1;
        while(low <= high){
        	if(A[low] == elem){
        		while(high>low){
        			if(A[high]==elem){
        				high--;
        				count++;
        			}
        			else{
        				break;
        			}
        		}
        		count++;
        		temp = A[low];
        		A[low] = A[high];
        		A[high]= temp;
        		high--;
        	}
        	else{
        		low++;
        	}
        }
        return (A.length - count);
    }
}

这种方法代码看起来有点复杂,其实还是很容易明白的。

第二种思路:i和j指针同时从头开始,当遇到等于elem的值,我们不管,直接把后面不等于elem的值直接往前填补。

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

这种方法比第一种方法更通俗易懂,代码也更简洁些。

抱歉!评论已关闭.