

LeetCode-268-丢失的数字
source link: https://segmentfault.com/a/1190000040679141
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

LeetCode-268-丢失的数字
丢失的数字
解法一:数组遍历题目描述:给定一个包含 [0, n] 中 n 个数的数组 nums ,找出 [0, n] 这个范围内没有出现在数组中的那个数。
进阶:
- 你能否实现线性时间复杂度、仅使用额外常数空间的算法解决此问题?
示例说明请见LeetCode官网。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
首先,获取数字的长度为n,根据根据公式
n*(n+1)/2
得到从0到n的数字相加之和为sum,由于nums数组中只缺少一个数,所以遍历数组,将sum减去数组中所有的元素,然后剩下的数字就是要返回的数。
public class LeetCode_268 { public static int missingNumber(int[] nums) { int n = nums.length; int sum = n * (n + 1) / 2; for (int num : nums) { sum -= num; } return sum; } public static void main(String[] args) { int[] nums = new int[]{9, 6, 4, 2, 3, 5, 7, 0, 1}; System.out.println(missingNumber(nums)); } }
【每日寄语】 最清晰的脚印,总是印在最泥泞的路上。
Recommend
-
32
全面战争:三国,268卖亏了 - 抽屉新热榜-聚合每日热门、搞笑、有趣资讯全面战争:三国,268卖亏了
-
19
罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。 字符 数值 I 1 V 5 X 10 L 50 C 100 D 500 M 1000 例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII...
-
12
LeetCode 第 201 号问题:数字范围按位与-五分钟学算法 当前位置:五分钟学算法 > LeetCodeAnimation > LeetCode 第 201 号问题:数字范围按位...
-
10
本文首发于公众号「五分钟学算法」,是图解 LeetCode 系列文章之一。 个人网站:https://www.cxyxiaowu.com
-
10
LeetCode 第 136 号问题:只出现一次的数字-程序员小吴 当前位置:程序员小吴 > LeetCodeAnimation > LeetCode 第 136 号问题:只出现一次的数...
-
20
Show notes Brad Frost joins us to talk about the nitty gritty of collaborating to create and manage design systems. We look back at the journey from responsive design to atomic...
-
11
About this Episode We are joined by Tanvir Ahmed from Okta to talk about why authentication can seem so hard, but really shouldn't be. We chat about how our devices that we carry around with us every day really sh...
-
5
Codeforces Round #268 Editorial Codeforces Round #268 Editorial
-
3
Lee Stott talks with us about how AI is a democratizing technology, the challenges in making sure AI is used responsibly, who the target audience is for AI, and the AI tools Lee Stott thinks are worth watching.
-
4
Episode 268: Democratizing AI or AI for Everyone with Lee Stott 00:00 43:52
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK