leetcode之Find All Duplicates in an Array 问题

来源:互联网 发布:钢琴可以自学吗 知乎 编辑:程序博客网 时间:2024/05/29 17:25

问题描述:

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array),some elements appear twice and others appear once.

Find all the elements that appear twice in this array.

Could you do it without extra space and in O(n) runtime?

题目要求找到相同的数,每个数的大小范围是1~n。要求给出的答案中时间复杂度是O(n),空间复杂度是O(1)

示例:

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[2,3]

题目来源:Find All Duplicates in an Array (具体地址:https://leetcode.com/problems/find-all-duplicates-in-an-array/#/description)

思路:题目给出的值的大小在1到n之间,而我们的数组索引在0~n-1,那我们就把它处理一下喽,变成0 ≤ a[i] - 1≤n - 1。接下来就是比较常见的数组索引的把戏了吧。具体参见下面代码吧。可以和Find All Numbers Disappeared in an Array  关联起来阅读,详细解答Find All Numbers Disappeared in an Array相关解答也给出来。

代码:





阅读全文
1 0
原创粉丝点击