# 数组反转
// T: O(n) S: O(1)
private static void reverse(int[] nums, int left, int right) {
while (left < right) {
swap(nums, left, right);
left++;
right--;
}
}
private static void swap(int[] nums, int idx1, int idx2) {
int tmp = nums[idx1];
nums[idx1] = nums[idx2];
nums[idx2] = tmp;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 二分查找
public static int binarySearch(int[] arr, int target) {
int lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = lo + ((hi - lo) >> 1);
if (arr[mid] > target) hi = mid - 1;
else if (arr[mid] < target) lo = mid + 1;
else return mid;
}
return lo;
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10