Remove Element 数组中删除给定元素 @ LeetCode

题目:

给定一个排序过的数组,要求in place的移除重复元素,返回处理后的数组长度


思路:

前后指针,一遍遍历数组即可
要点:
1 双指针,一开始两个指针i,j都指向第一个元素,特别注意1,1,2  删除1的情况
2 明确i的作用是指向下一个要被替换的位置,j的作用是找到下一个valid的数,然后用j指向的数来替换i指向的数


package Level1;
import java.util.Arrays;

/**
 * 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.
 */
// 这种题必须在纸上模拟一遍
public class S27 {

	public static void main(String[] args) {
		int[] A = {1,1,2,3};
		int elem = 1;
		System.out.println(removeElement(A, elem));
		System.out.println(Arrays.toString(A));
	}
	
	// O(n)
	public static int removeElement(int[] A, int elem) {
		if(A.length == 0){
			return 0;
		}
		if(A.length == 1){
			if(A[0] == elem){
				return 0;
			}else{
				return 1;
			}
		}
		
		int i = 0;		// i用来标示下一个要被替换的位置
		int j = 0;		// j用来找到下一个valid的数
		
		// 双指针固定格式
        while(i<A.length && j < A.length){
        	// j跳过invalid的数,直到找到valid的数
        	if(A[j] == elem){
        		j++;
        	}else{
        		A[i] = A[j];		// 替换invalid的数
        		i++;		// 更新标示
        		j++;
        	}
        }
        
        return i;
    }

}



public class Solution {
    public int removeElement(int[] A, int elem) {
        int len = A.length;
        if(len == 0){
            return 0;
        }
        if(len==1 && A[0]==elem){
            return 0;
        }
        
        int p=0, q=0;
        // 1 1 2
        while(q != len){
            if(A[q] == elem){
                q++;
            }else{
                A[p] = A[q];
                p++;
                q++;
            }
        }
        return p;
    }
}



  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值