Leecode_Missing number
2015-08-25 06:23
211 查看
The Problem:
Given an array containing n distinct numbers taken from
find the one that is missing from the array.
For example,
Given nums =
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
My wrong solution: Dichotomy
Right Solution: the sum of size+1 numbers - the sum of the array = the missing number
public class Solution {
public int missingNumber(int[] nums) {
int size = nums.length;
if(size < 1)
return 0;
else
{
int n1 = (size+1)*size/2;
int n2 = 0;
for(int i = 0; i<size; i++)
n2 = n2+nums[i];
return n1-n2;
}
}
}
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?
My wrong solution: Dichotomy
Right Solution: the sum of size+1 numbers - the sum of the array = the missing number
public class Solution {
public int missingNumber(int[] nums) {
int size = nums.length;
if(size < 1)
return 0;
else
{
int n1 = (size+1)*size/2;
int n2 = 0;
for(int i = 0; i<size; i++)
n2 = n2+nums[i];
return n1-n2;
}
}
}
相关文章推荐
- 【cocos2d-x 3.7 飞机大战】 决战南海I (十三) 分数场景
- 【cocos2d-x 3.7 飞机大战】 决战南海I (十二) 游戏结束场景
- 【cocos2d-x 3.7 飞机大战】 决战南海I (十一) 关于游戏场景
- 读《黑客与画家》
- 【小熊刷题】Validate Binary Search Tree <含recursion>
- Word Break II
- Leetcode: Lowest Common Ancestor of a Binary Tree
- Leetcode #131 Palindrome Partitioning
- jdbc如何传递java collection参数到procedure存储过程方法参数(db colleciton)
- ajax
- App Widget简单应用
- TCO 2015 2D
- Delphi控件的透明与不透明(要挨个解释一下原因),对InvalidateControl的关键理解
- STM32 SPI DMA 的使用
- The STM32 SPI and FPGA communication
- servlet jsp filter listener el表达式 tag file
- HOWTO: Use STM32 SPI half duplex mode
- 当tomcat已启动,但打不开tomcat主页
- 关于STM32 SPI NSS的讨论
- OpenGL中投影矩阵的推导