数组之双指针法(快慢指针法)

//数组的元素在内存地址中是连续的,不能单独删除数组中的某个元素,只能覆盖
public static void main(String[] args) {
    
    
        int[] a = {
    
    3, 2, 4, 7, 1, 10, 6, 9, 8, 5};
        int len = delNode(a, 3, 10);
        for(int i = 0; i < len; i++){
    
    
            System.out.print(a[i] + "  ");
        }
    }
    public static int delNode(int[] a, int x, int y){
    
    //删除介于x和y之间的所有元素
        int len = 0;
        for(int i = 0; i < a.length; i++){
    
    
            if(a[i] < x || a[i] > y){
    
    
                a[len] = a[i];
                len++;
            }
        }
        return len;
    }
    public static int delNode1(int[] a, int x, int y){
    
    //删除介于x和y之间的所有元素
        int slowIndex = 0;
        for(int fastIndex = 0; fastIndex < a.length; fastIndex++){
    
    
            if(a[fastIndex] < x || a[fastIndex] > y){
    
    
                a[slowIndex] = a[fastIndex];
                slowIndex++;
            }
        }
        return slowIndex;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_46497503/article/details/108982838