zoukankan      html  css  js  c++  java
  • [leetcode-268-Missing Number]

    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.

    Note:
    Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

    Credits:
    Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

    思路:

    The basic idea is to use XOR operation. We all know that a^b^b =a, which means two xor operations with the same number will eliminate the number and reveal the original number.
    In this solution, I apply XOR operation to both the index and value of the array. In a complete array with no missing numbers, the index and value should be perfectly corresponding( nums[index] = index), so in a missing array, what left finally is the missing number.

    int missingNumber(vector<int>& nums)
         {
             int ret = nums.size();
             for (int i = 0; i < nums.size();i++)
             {
                 ret = ret ^ i ^ nums[i];
             }
             return ret;
         }

    参考:

    https://discuss.leetcode.com/topic/24535/4-line-simple-java-bit-manipulate-solution-with-explaination

  • 相关阅读:
    魔兽登录系统
    航班信息查询预订
    第六章
    嵌套.
    嵌套
    Mysql
    第二章
    Java
    HTML-表格-列表-结构标记-表单
    HTML语言
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/7122541.html
Copyright © 2011-2022 走看看