leetcod--Missing Number
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.
解题思路:先求一遍不缺少情况下数组的和,然后减去缺少情况下数组的元素,差值就是缺少的元素。
#include <iostream>
#include<vector>
using namespace std;int missingNumber(vector<int>& nums)
{int n=nums.size();cout<<n<<endl;int sum=(0+n)*(n+1)/2;for(int i=0; i<n; i++) sum-=nums[i];return sum;
}
int main()
{vector<int> num;num.push_back(0);num.push_back(1);num.push_back(2);num.push_back(4);int s=missingNumber(num);cout<<s<<endl;}
拓展:如果要找到缺失的2个数呢?
package leedcode;import java.math.*;
import java.util.ArrayList;
import java.util.Arrays;public class test {public static ArrayList missingNumber(int[] nums) {ArrayList List = new ArrayList();Arrays.sort(nums);for (int i = 0; i < nums.length; i++) {if (nums[i] != i)List.add(i);}return List;}// 主方法public static void main(String[] args) {int[] s = { 0, 2, 4, 5, 6 };ArrayList r = missingNumber(s);System.out.println(r.get(1));}
}
不太好的一点就是开辟了新的空间。。。。。。。。。。
leetcod--Missing Number相关推荐
- PAT甲级1144 The Missing Number:[C++题解]哈希表
文章目录 题目分析 题目链接 题目分析 来源:acwing 分析: 把所有的数放进一个hash表,然后从1开始遍历,看每个数是不是在hash表中,输出第一个不在表中的元素. ac代码 #include ...
- 268. Missing Number
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missin ...
- Leet Code OJ 268. Missing Number [Difficulty: Medium]
题目: Given an array containing n distinct numbers taken from 0, 1, 2, -, n, find the one that is miss ...
- LeetCode之Missing Number
1.题目 Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is m ...
- 1144 The Missing Number (20 分)
Given N integers, you are supposed to find the smallest positive integer that is NOT in the given li ...
- C#LeetCode刷题之#268-缺失数字(Missing Number)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/4056 访问. 给定一个包含 0, 1, 2, ..., n 中 ...
- [Swift]LeetCode268. 缺失数字 | Missing Number
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ ➤微信公众号:山青咏芝(shanqingyongzhi) ➤博客园地址:山青咏芝(https://www.cnblog ...
- 268. Missing Number(缺失数字)
题目地址:https://leetcode.com/problems/missing-number/description/ Given an array containing n distinct ...
- 18年春季第一题 PAT甲级 1144 The Missing Number (20分) 上限感很重要
Given N integers, you are supposed to find the smallest positive integer that is NOT in the given li ...
- pta 1144 The Missing Number
Given N integers, you are supposed to find the smallest positive integer that is NOT in the given li ...
最新文章
- 小学计算机笔记,小学信息技术教师读书笔记
- ActiveMQ与xml rpc
- Android--视频播放器
- Triangle HDU - 5914
- Object C学习笔记13-Dictionary字典
- td外边加div为啥不隐藏_那些不常见,但却非常实用的 css 属性
- Python基础---时间模块 (二)
- 《低代码指南 》——LCHub应用参谋的适用场景
- 中国手机电视国家标准终于确定:T-MMB !, 但CMMB能答应吗?
- 企业邮箱文件被彻底删除怎么恢复?误删恢复有哪些方法呢?
- 目前国内常用的无纸化会议系统——迅控无纸化
- jieba 详细介绍
- linux中centos8.4配置静态ip
- 02 推荐算法-(01) Model-Based 协同过滤算法
- 复旦大学新冠肺炎防控第一课——尔雅答案
- Centos7 安装CUPS (安装斑马ZP450打印机驱动)
- mysql 显示行号
- 浅谈C语言内存(栈)
- Matlab之图像变换技术(十二)
- 与外文文献有关的那些事儿