(java)Missing Number
2016-03-03 00:35
567 查看
Given an array containing n distinct numbers taken from
For example,
Given nums =
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
思路:将1.....n加起来,然后减去nums[0].....nums[n-1]
代码如下(已通过leetcode)
public
int
missingNumber(int[]
nums) {
int
len =nums.length;
int
sum = (int)((len*(len+1))/2);
for(int
i: nums)
sum-=i;
return
sum;}
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?
思路:将1.....n加起来,然后减去nums[0].....nums[n-1]
代码如下(已通过leetcode)
public
int
missingNumber(int[]
nums) {
int
len =nums.length;
int
sum = (int)((len*(len+1))/2);
for(int
i: nums)
sum-=i;
return
sum;}
相关文章推荐
- 运行程序中出现的小问题
- Java图形界面
- java基础总结第一篇(JAVA简介)
- Spring MVC返回json数据的配置方式
- Java支持的数据类型有哪些?什么是自动拆装箱?
- spring RestTemplate用法详解
- spring异步线程的处理 @@Async介绍
- spring代码笔记
- java-tip-Collections.synchronized系列生成的容器
- Java集合基础 一 几个实现类之间的比较
- java 3S
- 关于java内存使用的相关问题(寄存器、栈、堆、静态存储、常理存储、非RAM存储)
- java 对象赋值是引用还是克隆
- 异常总结
- 如何在jmeter中调用自己写的java工具包
- JavaWeb----重定向请求sendRedirect、forward
- Java -----常量池
- 设计模式--单例模式
- Struts2 中测试 action
- java反射详解