We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
704.二分查找🤓🤓 思路分析:
二分查找法是一种在有序数组中查找某一特定元素的搜索算法。搜索过程从数组的中间元素开始,如果中间元素正好是要查找的元素,则搜索过程结束;如果某一特定元素大于或者小于中间元素,则在数组大于或小于中间元素的那一半中查找,而且跟开始一样从中间元素开始比较。如果在某一步骤数组为空,则代表找不到。这种搜索算法每一次比较都使搜索范围缩小一半
public int binarySearch(int[] nums, int target) { // 在区间[left,right]中查找元素,左闭右闭 int left = 0; int right = nums.length - 1; // 由于是在区间[left,right]中查找 // 因此当left=right时,区间内还有一个元素需要查找 while (left <= right) { // 计算中间点 int mid = left + (right-left)/2; // 如果target == nums[mid]则表示已经找到,返回mid if (target == nums[mid]) { return mid; // 如果target < nums[mid],表示目标值可能在左半边 } else if (target < nums[mid]){ // 由于是在左闭右闭的区间[left,right]中查找 // 而target < nums[mid],因此mid不再需要考虑 // 所以right = mid - 1,即在[left,mid-1]中继续查找 right = mid - 1; // 如果target > nums[mid],表示目标值可能在右半边 } else if (target > nums[mid]){ // 由于是在左闭右闭的区间[left,right]中查找 // 而target > nums[mid],因此mid不再需要考虑 // 所以left = mid + 1,即在[mid+1,right]中继续查找 left = mid + 1; } } // 未找到返回-1 return -1; }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
704.二分查找🤓🤓
思路分析:
The text was updated successfully, but these errors were encountered: