检查整数及其两倍数是否存在Java
文章发布较早,内容可能过时,阅读注意甄别。
# 题目
给你一个整数数组 arr,请你检查是否存在两个整数 N 和 M,满足 N 是 M 的两倍(即,N = 2 * M)。
更正式地,检查是否存在两个下标 i 和 j 满足:
- i != j
- 0 <= i, j < arr.length
- arr[i] == 2 * arr[j]
示例 1:
输入:arr = [10,2,5,3]
输出:true
解释:N = 10 是 M = 5 的两倍,即 10 = 2 * 5 。
示例 2:
输入:arr = [7,1,14,11]
输出:true
解释:N = 14 是 M = 7 的两倍,即 14 = 2 * 7 。
示例 3:
输入:arr = [3,1,7,11]
输出:false
解释:在该情况下不存在 N 和 M 满足 N = 2 * M 。
提示:
- 2 <= arr.length <= 500
- -10^3 <= arr[i] <= 10^3
# 思路
二分
# 解法
class Solution {
public boolean checkIfExist(int[] arr) {
arr = quickSort(arr);
int left = 0, right = arr.length - 1;
while(left <= right) {
int center = left + (right - left) / 2;
if(arr[center] < 0) left = center + 1;
else right = center - 1;
}
int centerIndex = left == arr.length ? left - 1 : left;
for(int i = centerIndex; i < arr.length - 1; i++) {
left = i + 1;
right = arr.length - 1;
while(left <= right) {
int center = left + (right - left) / 2;
if(arr[i] * 2 == arr[center]) return true;
else if(arr[i] * 2 > arr[center]) left = center + 1;
else right = center - 1;
}
}
for(int i = centerIndex; i > 0; i--) {
left = 0;
right = i - 1;
while(left <= right) {
int center = left + (right - left) / 2;
if(arr[center] == arr[i] * 2) return true;
else if(arr[center] < arr[i] * 2) left = center + 1;
else right = center - 1;
}
}
return false;
}
private int[] quickSort(int[] nums) {
if(nums.length <= 1) return nums;
quickSort(nums, 0, nums.length - 1);
return nums;
}
private void quickSort(int[] nums, int left, int right) {
if(left < right) {
int randomIndex = new Random().nextInt(right - left) + left + 1;
swapXOR(nums, randomIndex, left);
int povit = partition(nums, left, right);
quickSort(nums, left, povit - 1);
quickSort(nums, povit + 1, right);
}
}
private int partition(int[] nums, int left, int right) {
int index = left + 1;
for(int i = index; i <= right; i++) {
if(nums[i] < nums[left]) {
swapXOR(nums, index, i);
index++;
}
}
swapXOR(nums, left, index - 1);
return index - 1;
}
private void swapXOR(int[] nums, int left, int right) {
if(left == right) return;
nums[left] = nums[left] ^ nums[right];
nums[right] = nums[left] ^ nums[right];
nums[left] = nums[left] ^ nums[right];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# 总结
- 分析出几种情况,然后分别对各个情况实现