数组
寻找数组的中心索引
给你一个整数数组 nums ,请计算数组的 中心下标 。
数组 中心下标 是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。
如果中心下标位于数组最左端,那么左侧数之和视为 0 ,因为在下标的左侧不存在元素。这一点对于中心下标位于数组最右端同样适用。
如果数组有多个中心下标,应该返回 最靠近左边 的那一个。如果数组不存在中心下标,返回 -1 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public int findCenterIndex(int[] nums) {
int sum = 0; for (int i : nums) { sum += i; }
int leftNum = 0; for (int i = 0; i < nums.length; i++) { if (leftNum == (sum - leftNum - nums[i])) return i; leftNum += nums[i]; }
return -1; }
|
搜索插入位置
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n) 的算法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| public int searchInsertIndex(int[] nums, int target) {
if (nums.length == 0) { return 0; }
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] == target) { return mid; } else if (nums[mid] > target) { right = mid - 1; } else { left = mid + 1; } }
return left; }
|