java算法题:五键键盘 求连续子区间的和

五键键盘:

@Test
public void test01() {
    answer("1 1 5 1 5 2 4 4");
}

public void answer(String str) {
    String[] splitArr = str.split(" ");
    List<Integer> list = new ArrayList<>();
    List<Integer> tempList = new ArrayList<>();
    boolean flag = false;
    for (String s : splitArr) {
        switch (s) {
            //a
            case "1":
                if (flag) {
                    list.clear();
                    flag = false;
                }
                list.add(1);
                break;
            //ctrl c
            case "2":
                if (flag) {
                    tempList = ctrlC(list);
                }
                break;
            //ctrl x
            case "3":
                if (flag) {
                    tempList = ctrlX(list);
                    flag = false;
                }
                break;
            //ctrl v
            case "4":
                if(flag){
                    list.clear();
                }
                ctrlV(list, tempList);
                flag = false;
                break;
            //ctrl a
            case "5":
                flag = ctrlA();
        }
    }
    System.out.println(list.size());

}

public boolean ctrlA() {
    return true;
}

public List<Integer> ctrlC(List<Integer> list) {
    return new ArrayList<>(list);
}

public void ctrlV(List<Integer> list, List<Integer> cList) {
    list.addAll(cList);
}

public List<Integer> ctrlX(List<Integer> list) {
    List<Integer> xList = new ArrayList<>(list);
    list.clear();
    return xList;
}

求连续子区间的和

public static void main(String[] args) {
    Scanner scaner = new Scanner(System.in);
    int n = scaner.nextInt();
    int x = scaner.nextInt();
    int[] a = new int[n];
    for (int i = 0; i < n; i++) {
        a[i] = scaner.nextInt();
    }
    int count = 0;
    for(int i = 1; i < n+1;i++){
        for(int j = 0; j < n-i+1;j++){
            int sum = 0;
            for(int k = j ; k < j+i;k++){
                sum+=a[k];
            }
            if(sum>=x){
                count++;
            }
        }
    }
    System.out.println(count);
}

你可能感兴趣的:(leecode刷题记录,java,算法,开发语言)