1 找出数组中重复的数字
问题
长度为n的数组中,所有的数在0~n-1范围内。某些数字的重复的,但不知道有几个数字重复,重复了几次,找出任意一个重复的数字。
例子
{2,3,1,0,2,5,3}- - - -> 2或3
思路
- 先排序,再遍历找出arr[i]=arr[i-1]的数。T(n)=O(nlogn)
- 哈希表,空间换时间,key为数,value为出现的次数。T(n)=O(n)
代码
//哈希表
public static int solve2(int[] arr) {
Map<Integer,Integer> map = new HashMap<>();
for (int i : arr) {
map.put(i,map.getOrDefault(i,0)+1);
}
for (Integer i : map.keySet()) {
if (map.get(i)>1)
return i;
}
return -1;
}
// 快排
public static int solve(int[] arr) {
// Arrays.sort(arr);//快排
quickSort(arr,0,arr.length-1);
for (int i=1; i<arr.length; i++) {
if (arr[i]==arr[i-1])
return arr[i];
}
return -1;
}
public static void quickSort(int[] arr,int low, int high) {
if (low>=high) return;
int pivot_index=partition(arr,low,high);
quickSort(arr,low,pivot_index-1);
quickSort(arr,pivot_index+1,high);
}
public static int partition(int[] arr,int low, int high) {
int pivot_index=low;
int pivot=arr[low];
while(low<high) {
while (low<high && arr[high]>=pivot) high--;
while (low<high && arr[low]<=pivot) low++;
//交换
if (low<high) {
int t = arr[low];
arr[low] = arr[high];
arr[high] = t;
}
}
//low==high,如果不是已经排好,即high!=pivot_index
if (arr[high]!=pivot) {
int t = arr[high];
arr[high] = arr[pivot_index];
arr[pivot_index]=t;
}
return pivot_index;
}
#哈希表
def solve(arr:List[int])->int:
map = {};
for i in arr:
map[i]=map.get(i,0)+1
for i in map.keys():
if map[i]>1:
return i
return -1
#快排
def solve2(arr:List[int])->int:
# arr.sort(reverse=False)
quickSort(arr,0,len(arr)-1)
print(arr)
for i in range(1,len(arr)):
if arr[i]==arr[i-1]:
return arr[i]
return -1
def quickSort(arr:List[int],low:int,high:int)->None:
if low>=high: return None
pivot_index=partition(arr,low,high)
quickSort(arr,low,pivot_index-1)
quickSort(arr,pivot_index+1,high)
def partition(arr:List[int],low:int,high:int)->int:
pivot_index=low
pivot=arr[low]
while low<high:
while low < high and arr[high] >= pivot: high -= 1
while low<high and arr[low]<=pivot: low+=1
#交换
if low<high:
arr[low],arr[high]=arr[high],arr[low]
#low==high
if arr[high]!=arr[pivot_index]:
arr[pivot_index],arr[high]=arr[high],arr[pivot_index]
return pivot_index
2 不修改数组找出重复的数字
思路类似1,但只能用哈希表解法