Discuss / Java / 练习

练习

Topic source

Shuaixr2000

#1 Created at ... [Delete] [Delete and Lock User]

练习1:

static int findMissingNumber(int start, int end, List<Integer> list) {
        int last = 0;
        for (int i : list) {
            if (last != 0 && i - 1 != last) { // 如果减1不等于上一个数,被删除的就是上一个了
                return i - 1;
            }
            last = i;
        }
        return 0;
    }

练习2:



    static int findMissingNumber(int start, int end, List<Integer> list) {
        // 使用等差数列计算和
        int sum = (start + end) * (end - start+1) / 2;
        // 遍历数组并减去
        for (int i : list) {
            sum -= i;
        }
        // 剩下的数就是删除的数
        return sum;
    }

Shuaixr2000

#2 Created at ... [Delete] [Delete and Lock User]

什么鬼

ai爱耐耐

#3 Created at ... [Delete] [Delete and Lock User]

你这个练习1的方法如果删除的是两头的10或20,就不行了,不过方法二倒是通用


  • 1

Reply