leetcode268-确实数字

缺失数字

题目描述

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

示例 1:

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

示例 2:

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

code

方式一:


public class Leetcode268 {

    @Test
    public  void test(){
        int[] nums = new int[]{9, 6, 4, 2, 3, 5, 7, 0, 1};

        Solution solution = new Solution();
        System.out.println(solution.missingNumber(nums));
    }

    //找出蓄力中没有出现的数字
    class Solution {
        public int missingNumber(int[] nums) {
            Arrays.sort(nums);
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] != i) {
                    return i;
                }
            }
            return nums[nums.length-1]+1;
        }
    }
}

执行结果

9ms, 击败25.36%, 需要进行优化

时间复杂度

O(n*log n)

方式二

因为方式一中,使用了排序,所以消耗了大量的性能开销,需要进行优化,

使用异或的方式进行处理

class Solution {
        public int missingNumber(int[] nums) {
            //使用异或进行处理 4^4
            /**
             *  100
             *  100
             *  异或
             *  ----
             *  000
             */
            int res = nums.length;
            for (int i = 0; i < nums.length; ++i){
                res ^= nums[i];
                res ^= i;
            }
            return res;
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值