我正在尝试做我的任务。我认为我真的很接近解决它,但我不能这样做..我已经尝试过去几个小时了。
我想做什么:我有一个字符串和一个字符。我正在尝试实现二进制搜索以查找char,但它不会返回我想要的值。嗯,这是正确的,但我希望这段代码返回5而不是4。
这是我的代码,你可以帮我解决一下吗?没有排序方法,因为我不希望这里的代码超长,但请假设排序方法正确排序。如果您想查看排序方法,那么我可以为您上传。
我会感激任何帮助,因为我花了很多时间才这样做..:/。
public static void main(String[] args) {
String s = "abcdefg";
char c = 'e';
System.out.println(findRecursiveD(s, c));
}
public static int binarySearch(char[] a, char c, int start, int end) {
int mid = (start + end) / 2;
if(a[mid] == c)
return mid;
else if (a[mid] < c)
return binarySearch(a, c, mid+1, end);
else
return binarySearch(a, c, start, mid);
}
public static int findRecursiveD(String s, char c) {
int start = 0;
String S = s + c;
char[] b = S.toCharArray();
int end = b.length;
sort(b, 0, end);
String A = new String(b);
System.out.println(A);
return binarySearch(b, c, start, end);
}
}
答案 0 :(得分:0)
您的代码实际上是正确的,但您对正确索引的概念可能会失效。 Java中的数组是zero-indexed,这意味着数组的第一个元素实际上是0
,而不是1
。因此,在您提供的字符数组中,e
是第五个元素,但这意味着要访问它,您可以s[4]
来引用它。
如果您真的想要返回5
而不是4
,那么您只需在答案中添加一个。
答案 1 :(得分:0)
使用此:
System.out.println(findRecursiveD(s, c) + 1);
您需要添加一个,因为字符串中的第5个位置是位置4.第一个位置int eh string编号为0.如果您想要位置编号,则4是正确的答案。但是如果你想从1开始计算,那么你需要添加一个。
此外,您需要在start == end时终止搜索。你会遇到坏问题是start + 1大于end,所以你应该测试,并避免这种情况。当start == end,然后在验证位置mid(== start == end)的字符不是c之后,检查这个条件并返回一些特殊的东西,比如-1,或抛出异常。
public static int binarySearch(char[] a, char c, int start, int end) {
int mid = (start + end) / 2;
if(a[mid] == c) {
//now search for the 'last' character of that value
while (mid+1<a.length && a[mid+1]==c) {
mid++;
}
return mid;
}
else if (start==end) {
//if no character of that value found
return -1;
}
else if (a[mid] < c) {
return binarySearch(a, c, mid+1, end);
}
else {
return binarySearch(a, c, start, mid);
}
}
并删除将字符添加到要搜索的字符串中的语句。我不明白为什么添加值的开销会有所帮助,而且在搜索之前无论如何都要学习修改搜索数据似乎是一种糟糕的编码习惯。