AcWing 13. 找出数组中重复的数字
原题链接
简单
作者:
HelloZz
,
2021-01-04 09:52:47
,
所有人可见
,
阅读 323
算法1
(多次遍历) $O(n)$
时间复杂度
参考文献
java 代码
class Solution {
public int duplicateInArray(int[] nums) {
//数组为null或者数组长度为0返回-1
if(nums == null || nums.length == 0)
return -1;
//遍历一次数组判断数组中是否出现了负数或者大于等于n的数
for(int i = 0 ; i < nums.length ; i++){
if(nums[i] < 0 || nums[i] > nums.length)
return -1;
}
//创建标记数组,来标记nums[i]出现的次数
int[] target = new int[nums.length];
//用标记数组进行标记
for(int i = 0 ; i < nums.length ; i++)
target[nums[i]]++;
//最后遍历一次数组,返回第一个数组中重复的数字
for(int i = 0 ; i < nums.length ; i++){
if(target[nums[i]] > 1)
return nums[i];
}
return -1;
}
}
作者:18344163021
链接:https://www.acwing.com/solution/content/20861/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。