LeetCode 268 Missing Number

来源:互联网 发布:深圳网络运营策划公司 编辑:程序博客网 时间:2024/05/27 16:41

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?

给定一个含有n个数的数组,元素的范围是0~n,数组长度为n,而不是n+1,所以数组丢失了一个元素,请找到丢失的一个元素。数组不一定是排序的。

第一种做法:使用位运算,注意最后还要和n进行处理,因为数组的最后一位坐标为n-1.
public int missingNumber(int[] nums) {int result = 0;for (int i = 0; i < nums.length; i++) {result = result^nums[i];}return result^nums.length;}

第二种做法:
public int missingNumber2(int[] nums) {int result = 0;for (int i = 0; i < nums.length; i++) {result += i - nums[i];}return result + nums.length;}

第三种做法:
public int missingNumber2(int[] nums) {int result = (1 + nums.length) * nums.length / 2;for (int i = 0; i < nums.length; i++) {result -= nums[i];}return result;}


0 0
原创粉丝点击