LintCode --find-the-missing-number(寻找缺失的数)
2015-09-19 16:56
573 查看
原题链接:http://www.lintcode.com/zh-cn/problem/find-the-missing-number/
给出一个包含 0 .. N 中 N 个数的序列,找出0 .. N 中没有出现在序列中的那个数。
您在真实的面试中是否遇到过这个题?
Yes
样例
N =
注意
可以改变序列中数的位置。
分析:
遍历数组,将所有数加起来,计算应有的和与数组求和的差,即是缺失的数
时间复杂度 O(n)
代码(C++、Python、Java):
给出一个包含 0 .. N 中 N 个数的序列,找出0 .. N 中没有出现在序列中的那个数。
您在真实的面试中是否遇到过这个题?
Yes
样例
N =
4且序列为
[0, 1, 3]时,缺失的数为
2。
注意
可以改变序列中数的位置。
分析:
遍历数组,将所有数加起来,计算应有的和与数组求和的差,即是缺失的数
时间复杂度 O(n)
代码(C++、Python、Java):
class Solution { public: /** * @param nums: a vector of integers * @return: an integer */ int findMissing(vector<int> &nums) { // write your code here int n = nums.size(); int sum = 0; for (int i = 0; i < n; i++) sum += nums[i]; return n*(n+1)/2 - sum; } };
class Solution: # @param nums: a list of integers # @return: an integer def findMissing(self, nums): # write your code here l = len(nums) sum = 0 for i in range(l): sum = sum + nums[i] return (l)*(l+1)/2 - sum
public class Solution { /** * @param nums: an array of integers * @return: an integer */ public int findMissing(int[] nums) { // write your code here int n = nums.length; int sum = 0; for (int i = 0; i < n; i++) sum += nums[i]; return n*(n+1)/2 - sum; } }
相关文章推荐
- Subtree
- LintCode --number-of-airplanes-in-the-sky(数飞机)
- LintCode --invert-binary-tree(翻转二叉树)
- LintCode 翻转二叉树
- LintCode 寻找缺失的数
- Lintcode 比较字符串
- Lintcode 主元素
- Lintcode解题笔记 - 岛屿的个数
- LintCode -合并两个排序链表
- 20150708 lintcode 总结 Binary Tree Maximum Path Sum Show result *****
- 20150708 lintcode 总结 Minimum Path Sum
- 20150708 lintcode 总结 Binary Search Tree Iterator
- 20150707 lintcode 总结 Search Range in Binary Search Tree
- 20150624 lintcode 总结 binary-tree-level-order-traversal **
- 20150624 lintcode 总结 Lowest Common Ancestor
- 20150624 lintcode 总结 Balanced Binary Tree
- Lintcode(1)-两个字符串是变位词
- Lintcode(2)-比较字符串
- Lintcode(3)-字符串查找
- Lintcode(4)-乱序字符串