【LeetCode】268.Missing Number解题报告

【LeetCode】268.Missing Number解题报告

tags: Array

题目地址:https://leetcode.com/problems/missing-number/#/description
题目描述:

  Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.
  For example,Given nums = [0, 1, 3] return 2.

题意:一个无序的序列,0到n之间只缺少一个数,找出缺的那个数。

Solutions:

解法一:

  基本思想是使用异或运算。 我们都知道a ^ b ^ b = a,这意味着具有相同数字的两个xor操作将消除数字并显示原始数字。
  在此解决方案中,我将XOR运算应用于数组的索引和值。 在一个没有丢失数字的完整数组中,索引和值应完全对应(nums [index] = index),所以在一个缺少的数组中,最后剩下的是缺少的数字。
  下面是异或的运算法则

>

  1. a ⊕ a = 0
  2. a ⊕ 0 = a
  3. a ⊕ b = b ⊕ a
  4. a ⊕b ⊕ c = a ⊕ (b ⊕ c) = (a ⊕ b) ⊕ c;
  5. d = a ⊕ b ⊕ c 可以推出 a = d ⊕ b ⊕ c.
  6. a ⊕ b ⊕ a = b.
public class Solution {
    public int missingNumber(int[] nums) {
        int xor = 0, i = 0;
        for (i = 0; i < nums.length; i++) {
            xor = xor ^ i ^ nums[i];
        }
        return xor ^ i;
    }
}

解法二:

  因为只缺一个数,所有数几乎连续,求和容易。方法很巧!

public class Solution {
    public int missingNumber(int[] nums) {
        int sum = 0;
        for(int num: nums)
            sum += num;

        return (nums.length * (nums.length + 1) )/ 2 - sum;
    }
}

Date:2017年6月7日

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值