移除元素

import java.util.Scanner;

public class demo {
    public static void main(String[] args) {
        //移除数组中的某个元素
        //因为数组空间是连续的,暴力方法移除后让该数后面的地址都前进一位
        Scanner sc = new Scanner(System.in);
        String str =  sc.nextLine();
        int target = sc.nextInt();//需要移除的元素值
        String [] strs = str.split(" ");
        int [] arr = new int[strs.length];
        for (int i = 0; i < strs.length; i++) {
            arr[i] = Integer.parseInt(strs[i]);
        }

        //暴力
//        int length = arr.length;
//        for (int i = 0; i < arr.length; i++) {
//            if (arr[i] == target) {
//                for (int j = i + 1; j < arr.length; j++) {
//                    arr [j - 1] = arr[j];
//                }
//                i--;
//                length -- ;
//            }
//        }
//        for (int i = 0; i < length; i++) {
//            System.out.print(arr[i] + " ");
//        }

        //双指针
        int slow = 0;
        for (int fast = 0;fast < arr.length;fast++) {
            if (arr[fast] != target) {
                arr[slow] = arr[fast];
                slow++;
            }
        }
        for (int i = 0; i < slow; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务