[英]Find Two elements in the Array that add up to the Target number in O(n * log n) Time
[英]Solving a LeetCode problem to find first and last index of target in array in O(log n)
我已經解決了一個leet 代碼問題。 問題問:
給定一個按非降序排序的整數數組 nums,找到給定目標值的開始和結束位置。
如果在數組中找不到目標,則返回 [-1, -1]。
您必須編寫一個具有 O(log n) 運行時復雜度的算法。
輸入:nums = [5,7,7,8,8,10],目標 = 8
輸出:[3,4]
輸入:nums = [5,7,7,8,8,10],目標 = 6
輸出:[-1,-1]
輸入:nums = [],目標 = 0
輸出:[-1,-1]
這是我的解決方案(使用二進制搜索),但我實際上不確定這是否是 O(log n),因為我的答案的運行時間是 6 毫秒。
public static int[] returnIndices = new int[2];
public int[] searchRange(int[] nums, int target) {
int[] resultArr = new int[2];
if(nums.length == 0 && target == 0) {
resultArr[0] = -1;
resultArr[1] = -1;
System.out.print(resultArr[0] + "," + resultArr[1]);
return resultArr;
}
binarySearch(nums, target);
resultArr = getIndexOf();
System.out.print(resultArr[0] + "," + resultArr[1]);
return resultArr;
}
public int[] getIndexOf() {
return returnIndices;
}
public int[] setIndex(int index) {
if(index == -1) {
returnIndices[0] = -1;
returnIndices[1] = -1;
}
else {
int lastIndex = index + 1;
returnIndices[0] = index;
returnIndices[1] = lastIndex;
}
return returnIndices;
}
public int binarySearch(int[] nums, int target) {
int low = 0;
int high = nums.length;
int mid = 0;
while(low <= high) {
mid = low+high/2;
if(nums[mid] == target) {
setIndex(mid);
return mid;
}
if(nums[mid] < target) {
low = mid+1;
}
if(nums[mid] > target) {
high = mid-1;
}
}
setIndex(-1);
return -1;
}
我的提交需要 0 毫秒,你的實際上返回錯誤的結果。 這個想法是數組不遞減但包含重復項,但盡管存在重復項,您仍然可以使用二進制搜索:您只需要再次使用二進制搜索將找到的索引提升到左側和右側,但具有其他邊界。
while(low <= high) {
// that is not correct
// must be either (low + high)/2
// or (low + high) >>> 2
mid = low+high/2;
if(nums[mid] == target) {
setIndex(mid);
// here you should not return
// you need to save mid, and
// depending on what boundary
// you are looking promote it
// either to the left or to the right
return mid;
}
if(nums[mid] < target) {
low = mid+1;
}
if(nums[mid] > target) {
high = mid-1;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.