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;
}

  • 1

Reply