LeetCode 268 -Missing Number ( JAVA )

来源:互联网 发布:大麦电话软件下载 编辑:程序博客网 时间:2024/06/06 17:33

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?



public class Solution {    public int missingNumber(int[] nums) {        Arrays.sort(nums);        if(nums.length == 0|| nums[0]!=0 ){            return 0;        }        for(int i=0;i<nums.length-1;i++){            if(nums[i+1]-nums[i]!=1){                return nums[i+1]-1;            }        }        return nums.length;    }}





总结:题目很简单,考虑一下边界问题,一个循环搞定,就是效率太低了,O(N),于是我又换了个思路结果是打败了20%,效率还是不高,时间复杂度一样。

public class Solution {    public int missingNumber(int[] nums) {       int sum = 0;       int tmp = 0;       for(int n:nums){           sum += n;       }       for(int i=1 ; i <= nums.length ; i++){           tmp+=i;       }       return tmp-sum;    }}





0 0
原创粉丝点击