内容简介:leetcode No448题目的意思是,有一个不用额外的空间,从数值大小的设定上来看,可以将数值和数组的索引关联起来,出现过的数,我们可以将对应索引上标记为负数,第二次出现时,如果索引上的值已被标记为负数,我们就知道它其实已经出现过一次啦~
题目一:Find All Duplicates in an Array
1、题目链接
leetcode No448 https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/
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? Example: Input: [4,3,2,7,8,2,3,1] Output: [2,3]
2、Solution
题目的意思是,有一个 n
个数的数组,每个数的大小都在 [1,n]
之间,有的数出现了 2
次,有的数出现了 1
次。找到出现2次的数。
不用额外的空间,从数值大小的设定上来看,可以将数值和数组的索引关联起来,出现过的数,我们可以将对应索引上标记为负数,第二次出现时,如果索引上的值已被标记为负数,我们就知道它其实已经出现过一次啦~
go版的代码如下:
func findDuplicates(nums []int) []int {
var res []int
for i:=0;i<len(nums);i++{
index := abs(nums[i])-1
if nums[index] <0 {
res =append(res,index+1)
}
nums[index] = -nums[index]
}
return res
}
func abs(num int) int{
if num <0 {
return -num
}
return num
}
题目二:Find All Numbers Disappeared in an Array
1、题目链接
leetcode No448: https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this array. Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. Example: Input: [4,3,2,7,8,2,3,1] Output: [5,6]
2、Solution
其实这个和题目一的思路几乎一模一样。
题目的意思是,有一个 n
个数的数组,每个数的大小都在 [1,n]
之间,有的数出现了 2
次,有的数出现了 1
次。找到没有出现过的数。
不用额外的空间,从数值大小的设定上来看,可以将数值和数组的索引关联起来,出现过的数,我们可以将对应索引上标记为负数,遍历一遍,不是负数的索引,就是一次都没有出现过的数啦~
golang的代码如下
func findDisappearedNumbers(nums []int) []int {
var res []int
for i:=0;i<len(nums);i++ {
index := nums[i] -1
if(nums[i] < 0){
index = nums[i]*(-1) - 1
}
if(nums[index] > 0){
nums[index] = nums[index] * (-1)
}
}
for i:=0;i<len(nums);i++{
if(nums[i]>0){
res = append(res,i+1)
}
}
return res
}
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- C语言指针数组和数组指针
- 数组 – 如何在Swift中将数组拆分成两半?
- 菜鸡的算法修炼:数组(旋转数组的最小数字)
- 交换数组元素,使得数组的和的差最小
- JS数组专题1️⃣ ➖ 数组扁平化
- 算法-计算小数组在大数组中的索引
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
世界是平的(3.0版)
[美] 托马斯·弗里德曼 / 何帆、肖莹莹、郝正非 / 湖南科学技术出版社 / 2008-9 / 58.00元
世界变得平坦,是不是迫使我们跑得更快才能拥有一席之地? 在《世界是平的》中,托马斯·弗里德曼描述了当代世界发生的重大变化。科技和通信领域如闪电般迅速的进步,使全世界的人们可以空前地彼此接近——在印度和中国创造爆炸式增长的财富;挑战我们中的一些人,比他们更快占领地盘。3.0版新增两章,更新了报告和注释方面的内容,这些内容均采自作者考察世界各地特别是整个美国中心地带的见闻,在美国本土,世界的平坦......一起来看看 《世界是平的(3.0版)》 这本书的介绍吧!