[英]Fixed Point (Value equal to index) in a given array - 1 indexed using binary search
[英]Finding an element in an array such that the index is equal to its value using binary search
我在升序的陣列,由正整數,並用條件重復不在陣列allowed.In我必須找到米,使得array[m]=m
使用二進制搜索我在下面的代碼中使用:
public class Main {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
int n = a.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = a.nextInt();
}
int result = binarysearch(arr,n);
if(result!=-1)
System.out.println(result);
else
System.out.println("NOT_FOUND");
}
public static int binarysearch(int[] array,int n){
int start=1,end=n;
while(start<=end){
int mid = (start+end)/2;
if(mid==array[mid-1])
return mid;
else if(mid<array[mid-1])
end=mid-1;
else
start=mid+1;
}
return -1;
}
請注意,數組是 1 索引而不是 0 索引我面臨的問題是當我嘗試以下情況時: array={1,2,3,4,5}
預期output is 1
但由於二分搜索該方法returns 3
作為輸出。 是否有任何解決方法可以繞過此類案例?
查看條件:“我有一個按升序排列的數組,由正整數組成,並且條件重復是不允許的”
這個問題有一個簡單的解決方案。
public static int binarysearch(int[] array,int n){
If(a[0] == 1) return 1;
else return -1;
}
因為如果數組中的第一個數字不是 1,則數組的其余部分將不會有任何等於其索引的值。
解釋:
假設數組有項 a1, a2, a3 ... an,其中沒有項相等且 aj < ak 如果 j < k
問題本質上是找到一個術語 ai,其中 ai = i
如果 a1 不是 1,則根據條件 #2,它必須大於 1。
根據條件 1 和 3,a2 必須大於 2。然后,a3 必須大於 3,依此類推。 項 an 必須大於 n。 產生無解。
另一方面,如果 a1 為 1,則您擁有該術語並且可以返回它。
您的代碼看起來大部分是正確的,但您不應該假設用戶輸入時數組已經排序。
我認為真正的問題在於理解二分搜索的工作原理。 二分查找總是從數組的中間開始。 因此,如果您提供輸入 {1, 2, 3, 4, 5},您將始終得到 3,因為算法從中間搜索並注意到數字 3 等於其索引。
如果您的目標是找到最小整數 m 使得 a[m] 等於 m,那么您不應該使用二分查找。 相反,您應該從數組的開頭開始(因為我們假設它是按升序排序的)並使用線性搜索:
for (int i = 0; i < n; ++i) {
if (a[i] == i) {
return i;
}
}
return -1;
像上面這樣的東西應該給出預期的結果。 (請注意,上面使用了基於 0 的索引邏輯,但您應該能夠根據需要對其進行調整。此外,Java 中的數組始終是 0 索引的,因此您可能需要仔細檢查您是否正確理解了問題。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.