Skip to content

Commit

Permalink
'1'
Browse files Browse the repository at this point in the history
  • Loading branch information
Ainevsia committed Jul 15, 2023
1 parent 2fa4082 commit ae4dae5
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions notes/src/day1/lc704.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,66 @@

## 解题思路

直接使用标准库的做法,slice的partition_point没有找到的时候返回数组的长度

```rust
impl Solution {
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
let x = nums.partition_point(|&x| x < target);
if x == nums.len() { return -1 }
if nums[x] == target { return x as i32 }
-1
}
}
```

手写的二分查找

```rust
impl Solution {
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
let mut left = 0;
let mut right = nums.len();
while left < right {
let mid = left + (right - left) / 2;
if nums[mid] < target {
left = mid + 1
} else if nums[mid] > target {
right = mid;
} else {
return mid as i32
}
}
-1
}
}
```


## 学习感想

对区间的定义没有想清楚,**区间的定义就是不变量**,在操作的过程中 保持不变量

在左闭右闭区间的情况下 由于right 要 -1,所以要考虑right=0 - 1的情况

```rust

impl Solution {
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
let mut left = 0isize;
let mut right = nums.len() as isize - 1;
while left <= right {
let mid = (left + (right - left) / 2) as usize;
if nums[mid] < target {
left = mid as isize + 1
} else if nums[mid] > target {
right = mid as isize - 1;
} else {
return mid as i32
}
}
-1
}
}
```

0 comments on commit ae4dae5

Please sign in to comment.