3.數組中重複的數字
題目描述
在一個二維數組中(每個一維數組的長度相同),每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數。
1.HashSet
使用hashSet去重 如果添加不成功說明出現了重複的元素 返回。
public int findRepeatNumber(int[] nums) {
if(nums.length == 0 || nums.length <2){
return -1;
}
Set<Integer> set = new HashSet<Integer>();
int repeat = -1;
for (int num : nums) {
if (!set.add(num)) {
repeat = num;
break;
}
}
return repeat;
}
時間複雜度:O(n)
2.利用下標
將數組中的元素當成下標存儲到數組中去,如果沒有重複的就說明無重複數 否則有重複數字
public boolean duplicate(int[] nums, int length, int[] duplication) {
if (nums == null || length <= 0)
return false;
for (int i = 0; i < length; i++) {
while (nums[i] != i) {
if (nums[i] == nums[nums[i]]) {
duplication[0] = nums[i];
return true;
}
swap(nums, i, nums[i]);
}
}
return false;
}
private void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
時間複雜度:O(n)