LeetCode刷题:268. Missing Number

LeetCode刷题:268. Missing Number

原题链接:https://leetcode.com/problems/missing-number/

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

Example 1:

Input: [3,0,1]
Output: 2
Example 2:

Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?


算法设计

class Solution {
    public int missingNumber(int[] nums) {
        int sum1 = 0;
        for (int i = 0; i < nums.length; i++) {
            sum1 += nums[i];
        }
        
        int sum2 = 0;
        for (int j = 0; j <= nums.length; j++) {
            sum2 += j;
        }
        
        return Math.abs(sum1 - sum2);
    }
}

很简单的一个算法设计思路,利用差值求解。

LeetCode上提交代码,Accepted!

上一篇:268 - Missing Number


下一篇:ccs使用中出现的一些关于makefile的问题