• 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?


     题目标签:Array

      题目给了我们一个nums array, array 里是从0 到n 的所有数字, 但是会缺失一个,让我们找出来,数字的排列不是有序的。

      既然我们知道n,而且数字是从0 到 n 的,可以利用等差数列求和公式 (首项+尾项) * 个数/2 求出总和, 再遍历一次nums 算出实际的sum, 然后差值就是缺失的那个数字了。

    Java Solution:

    Runtime beats 49.88% 

    完成日期:04/27/2017

    关键词:Array

    关键点:等差数列求和公式

     1 class Solution 
     2 {
     3     public int missingNumber(int[] nums) 
     4     {
     5         int cSum = (0 + nums.length) * (nums.length + 1) / 2;
     6         int sum = 0;    
     7         
     8         for(int i=0; i<nums.length; i++)
     9         {
    10            sum += nums[i];
    11         }
    12         
    13         return cSum - sum;
    14     }
    15 }

    参考资料:N/A

    LeetCode 题目列表 - LeetCode Questions List

    题目来源:https://leetcode.com/

  • 相关阅读:
    NAT基本原理及应用
    端口转发和端口映射的区别
    Xshell不能连接Kali系统SSH的解决
    PowerSploit
    powertool
    Windows/Linux 下反弹shell
    Apache Shiro 反序列化漏洞复现(CVE-2016-4437)
    渗透测试神器Cobalt Strike使用教程
    Notepad++ 小技巧
    Linux:Day44(上)
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7497613.html
Copyright © 2020-2023  润新知