当前位置:网站首页>[array] binary search
[array] binary search
2022-07-02 23:32:00 【Alson_ Code】
1、 The basic idea
Prerequisite : Ordered array + No repeating elements ( not essential )
Put the array ( Default ascending order ) Separate from the middle , Compare with the intermediate value every time , If it is less than the middle value, you only need to find the left , If it is greater than the middle value, just look for the right , Equal to the intermediate value and directly return the subscript !
2、 Exercises ( It is suggested to go first leetcode do , Then look at the answer )
// Mode one : Left and right closed [left,right]
class Solution {
public int search(int[] nums, int target) {
// Closed interval :r=nums.length-1
int l = 0;int r = nums.length - 1;
// Be careful :l<=r
// Why is there an equal sign ?
// [1], When there's only one element ,l=0,r=0,m=0,l==r It makes sense
while (l <= r){
int m = l + (r - l) / 2;
if (nums[m] == target) return m;
else if (nums[m] > target) {
// Closed interval , So it is r=m-1
r = m - 1;
}else{
l = m + 1;
}
}
return -1;
}
}
// Mode one : Left closed right away [left,right)
class Solution {
public int search(int[] nums, int target) {
// Open range :r=nums.length
int l = 0;int r = nums.length;
// [1], When there's only one element ,l=0,r=1,m=0, Elements can be compared , therefore l==r You can quit , It doesn't make sense
while (l < r){
int m = l + (r - l) / 2;
if (nums[m] == target) return m;
else if (nums[m] > target) {
// Open range , So it is r=m
r = m;
}
else {
l = m + 1;
}
}
return -1;
}
}
// Method 1 : Brute force
// Traversal array , Find insertion location
// If there is this element, the position is the insertion position ; Without this element , Then the first array position larger than the target element is the insertion position
class Solution {
public int searchInsert(int[] nums, int target) {
for (int i = 0; i < nums.length; i ++) {
if (nums[i] >= target) return i;
}
return nums.length;
}
}
// Method 2 : Two points search
// If this element exists in the array , Use bisection to find the position of this element and return
// Without this element , be r The position of is exactly smaller than the position of the target element , be r+1 It's where you need to insert
class Solution {
public int searchInsert(int[] nums, int target) {
int l = 0; int r = nums.length - 1;
while (l <= r){
int m = l + (r - l) / 2;
// Equal to an element
if (nums[m] == target) return m;
else if (nums[m] > target) {
r = m - 1;
}else{
l = m + 1;
}
}
// Leftmost
// Far right
// After an element
return r + 1;
}
}
// Method 1 : Two points search
// First, find the position of the element by bisection ( Because the position of repeated elements is not necessarily the leftmost or rightmost ), Then slide the pointer on the left to find the leftmost , Slide right until you find the rightmost
class Solution {
public int[] searchRange(int[] nums, int target) {
int index = binarySearch(nums, target);
if (index == -1) {
return new int[]{
-1, -1};
}
// Left slide pointer
int left = index;
while (left - 1 >= 0 && nums[left - 1] == target){
left = left - 1;
}
// Slide the pointer right
int right = index;
while (right + 1 < nums.length && nums[right + 1] == target){
right = right + 1;
}
return new int[]{
left, right};
}
public int binarySearch(int[] nums, int target){
int l = 0; int r = nums.length - 1;
while (l <= r){
int m = l + (r - l) / 2;
if (nums[m] == target) return m;
else if (nums[m] > target) r = m - 1;
else l = m + 1;
}
return -1;
}
}
// Method 2 : Two points search
// If the element exists , Find the left and right boundaries through binary search
// If the element does not exist, return directly {-1,-1}
class Solution {
public int[] searchRange(int[] nums, int target) {
int leftBorder = getLeftBorder(nums, target);
int rightBorder = getRightBorder(nums, target);
// Only if any boundary is not found, there is no such element
if (rightBorder == -2 || leftBorder == -2){
return new int[]{
-1, -1};
}
// The left and right boundaries are open intervals , As long as it exists, the interval must be greater than 1
if (rightBorder - leftBorder > 1){
return new int[]{
leftBorder + 1, rightBorder - 1};
}
return new int[]{
-1, -1};
}
// Find the left boundary , This left boundary is required +1 Of
// The left boundary is to find the first position smaller than the target value step by step from the right
public int getLeftBorder(int[] nums, int target){
int l = 0; int r = nums.length - 1;
int leftBorder = -2;
while (l <= r){
int m = l + (r - l) / 2;
// If the intermediate value is greater than or equal to the target value , be r = m - 1; At the same time, update the value of the left boundary
if (nums[m] >= target){
r = m - 1;
leftBorder = r;
}else{
l = m + 1;
}
}
return leftBorder;
}
// Find the right boundary , This right boundary is required -1 Of
// Right border , Is to find the first position larger than the target value from the right
public int getRightBorder(int[] nums, int target){
int l = 0; int r = nums.length - 1;
int rightBorder = -2;
while (l <= r){
int m = l + (r - l) / 2;
if (nums[m] > target){
r = m - 1;
}else{
// If the intermediate value is less than or equal to the target value , be l = m + 1; At the same time, update the value of the right boundary
l = m + 1;
rightBorder = l;
}
}
return rightBorder;
}
}
// Method 1 : Brute force
// Traverse x, Know that the square of the first number is greater than the target value
class Solution {
public int mySqrt(int x) {
// x = 0 A special case
int res = 0;
// x = 1 A special case
if (x == 1) res = 1;
for (long i = 1; i <= x / 2; i++){
long tmp = i * i;
if (tmp > x){
res = (int)i - 1;
break;
}else{
res = (int)i;
}
}
return res;
}
}
// Method 2 : Two points search
// from 0 To x, Find... By bisection , If the flat hair of a certain number is exactly equal to x Then return directly
// If there is no direct equal , be r Is the nearest integer value
class Solution {
public int mySqrt(int x) {
int l = 0; int r = x;
while (l <= r){
long m = l + (r - l) / 2;
long tmp = m * m;
if (tmp == x){
return (int)m;
}else if (tmp > x){
r = (int) m - 1;
}else{
l = (int) m + 1;
}
}
return r;
}
}
// Two points search
// from 0 To num, If the flat hair of a certain number is exactly equal to num, Then return to true, Otherwise return to false
class Solution {
public boolean isPerfectSquare(int num) {
int l = 0; int r = num;
while (l <= r){
long m = l + (r - l) / 2;
long tmp = m * m;
if (tmp == num){
return true;
}else if (tmp > num){
r = (int) m - 1;
}else{
l = (int) m + 1;
}
}
return false;
}
}
Thanks for reading , I am a Alson_Code, One likes to complicate simple problems , A program that simplifies complex problems !
边栏推荐
- 【Proteus仿真】51单片机+LCD12864推箱子游戏
- ADC of stm32
- A single element in an ordered array -- Valentine's Day mental problems
- (stinger) use pystinger Socks4 to go online and not go out of the network host
- Brief introduction to common sense of Zhongtai
- Explain promise usage in detail
- Implementation of VGA protocol based on FPGA
- Go basic data type
- What experience is there only one test in the company? Listen to what they say
- Getting started with golang: for Range an alternative method of modifying the values of elements in slices
猜你喜欢
Speech recognition Series 1: speech recognition overview
Integration of revolution and batch normalization
[adjustment] postgraduate enrollment of Northeast Petroleum University in 2022 (including adjustment)
Win11系统explorer频繁卡死无响应的三种解决方法
Compose 中的 'ViewPager' 详解 | 开发者说·DTalk
【Redis笔记】压缩列表(ziplist)
MySQL基础
采用VNC Viewer方式远程连接树莓派
详解Promise使用
Win11如何开启目视控制?Win11开启目视控制的方法
随机推荐
php 获取真实ip
I've been interviewed. The starting salary is 16K
富滇银行完成数字化升级|OceanBase数据库助力布局分布式架构中台
Highly available cluster (HAC)
Brief introduction to common sense of Zhongtai
Win11启用粘滞键关闭不了怎么办?粘滞键取消了但不管用怎么解决
Data set - fault diagnosis: various data and data description of bearings of Western Reserve University
[proteus simulation] 51 MCU +lcd12864 push box game
Interface switching based on pyqt5 toolbar button -1
How can cross-border e-commerce achieve low-cost and steady growth by laying a good data base
Where is the win11 microphone test? Win11 method of testing microphone
SharedPreferences save list < bean > to local and solve com google. gson. internal. Linkedtreemap cannot be cast to exception
Deep analysis of data storage in memory - C language
[analysis of STL source code] imitation function (to be supplemented)
Numerical solution of partial differential equations with MATLAB
Is 408 not fragrant? The number of universities taking the 408 examination this year has basically not increased!
Use of recyclerview with viewbinding
Potplayer set minimized shortcut keys
Arduino - character judgment function
"A good programmer is worth five ordinary programmers!"