标签:
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?
因为输入数组是0,1,2,...,n。 把nums[i]放到i的位置上. nums[i] != i的即为missing number.
注意6-9行不可先令 temp = nums[i]
1 public class Solution { 2 public int missingNumber(int[] nums) { 3 int res = nums.length; 4 for (int i=0; i<nums.length; i++) { 5 if (nums[i] < nums.length && nums[i] != i) { 6 int temp = nums[nums[i]]; 7 nums[nums[i]] = nums[i]; 8 nums[i] = temp; 9 i--; 10 } 11 } 12 for (int i=0; i<nums.length; i++) { 13 if (nums[i] != i) res = i; 14 } 15 return res; 16 } 17 }
标签:
原文地址:http://www.cnblogs.com/EdwardLiu/p/5071932.html