LeetCode268:缺失数字(JAVA题解)

题目描述:

给定一个包含 0, 1, 2, …, n 中 n 个数的序列,找出 0 … n 中没有出现在序列中的那个数。

示例1

输入: [3,0,1]
输出: 2

示例2

输入: [9,6,4,2,3,5,7,0,1]
输出: 8

这里先来说下思路:

  1. 排序后查找不相连的数字
    因为给定的数组中数字的范围只会存在于【0,ArrayLength】之中 所以排序后不想连两个数字的中间数即为缺失数字
    这个方法我一开始没想到,是看题解想到的直接附上leetcode代码
class Solution {
    public int missingNumber(int[] nums) {
        Arrays.sort(nums);

        // 判断 n 是否出现在末位
        if (nums[nums.length-1] != nums.length) {
            return nums.length;
        }
        // 判断 0 是否出现在首位
        else if (nums[0] != 0) {
            return 0;
        }

        // 此时缺失的数字一定在 (0, n) 中
        for (int i = 1; i < nums.length; i++) {
            int expectedNum = nums[i-1] + 1;
            if (nums[i] != expectedNum) {
                return expectedNum;
            }
        }

        // 未缺失任何数字(保证函数有返回值)
        return -1;
    }
}
  1. 将数组保存在另一个数组中 下标和值对应,然后遍历该数组 寻找值为零的下标并返回
    值得注意的一点:新建数组的长度应为原数组长度+1
    代码如下:
class Solution {
    public int missingNumber(int[] nums) {
        int[] results = new int[nums.length + 1];
        for(int i : nums) results[i] = i;
        for(int i = 0; i < results.length; i++) {
            if(results[i] == 0 && i != 0) {
                return i;
            }
        }
        return 0; 
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值