英文:
Find first occurrence of an integer in a sorted list with duplicates
问题
这段代码在数组中正确打印了元素"k"的第一个出现位置,但是我正在处理的问题要求我在数组中根本不存在元素"k"的情况下打印-1。我知道这很简单,但我卡住了,感到很沮丧,有人能帮忙吗?
n = sc.nextInt();
k = sc.nextInt();
int arr[] = new int[n];
for(int i=0; i<n; i++) {
arr[i] = sc.nextInt();
}
int foundIndex = -1;
for(int i=0; i<n; i++) {
if(arr[i] == k) {
foundIndex = i;
break;
}
}
System.out.println(foundIndex);
英文:
This code prints the first occurence of element 'k' in the array properly but the question I'm doing wants me to print -1 if the element 'k' is entirely not present in the array. I know its easy but I'm just stuck and its frustatiting any help?
n = sc.nextInt();
k = sc.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++) {
arr[i] = sc.nextInt();
}
for(int i=0;i<n;i++) {
if(arr[i]==k) {
System.out.println(i);
break;
}
}
答案1
得分: 1
int firstIndexOf(int[] sortedArray, int x) {
int p = Arrays.binarySearch(sortedArray, x);
if (p < 0) {
return -1;
}
while (p > 0 && sortedArray[p - 1] == x) {
--p;
}
return p;
}
二分查找将搜索范围反复分成两半,确定继续搜索的半边。它会返回找到的位置,或是插入位置的补码(~p)。
英文:
Use Arrays#binarySearch:
int firstIndexOf(int[] sortedArray, int x) {
int p = Arrays.binarySearch(sortedArray, x);
if (p < 0) {
return -1;
}
while (p > 0 && sortedArray == x) {
--p;
}
return p;
}
Binary search splits the searched range in half repetively looking in which half to continue. It returns either the found position or the complement (~p) of the insert position.
答案2
得分: 0
你在标题中提出的问题和你在帖子正文中提出的问题是两个不同的问题;然而,如果我们遵循你问题的正文,那与二分搜索毫无关系,引入布尔标志将使你得到你所要求的:
boolean notFound = true;
for(int i=0; i<n; i++) {
if(arr[i] == k) {
System.out.println(i);
notFound = false;
break;
}
}
if(notFound) System.out.println("-1");
英文:
What you are asking in the title, and what you are asking in the post body, are two different questions; however, if we will follow your question's body, that has nothing to do with binary search, and introducing boolean flag would get you what you are asking for:
boolean notFound = true;
for(int i=0; i<n; i++) {
if(arr[i] == k) {
System.out.println(i);
notFound = false;
break;
}
}
if(notFound) System.out.println("-1");
答案3
得分: 0
int findOccurenceOfElemet(int[] a, int k) {
if(a.length == 0) {
return -1;
}
for(int i = 0; i < a.length; i++) {
if(a[i] == k) {
return i;
}
}
// 如果未找到元素,返回-1
return -1;
}
英文:
int findOccurenceOfElemet(int[] a, int k) {
if(a.length == 0) {
return -1;
}
for(int i = 0; i < a.length; i++) {
if(a[i] == k) {
return i;
}
}
//return -1 if element not found
return -1;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论