mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
0035.搜索插入位置和Java版本
This commit is contained in:
@ -205,9 +205,36 @@ public:
|
||||
|
||||
## 其他语言版本
|
||||
|
||||
|
||||
Java:
|
||||
|
||||
```java
|
||||
class Solution {
|
||||
public int searchInsert(int[] nums, int target) {
|
||||
int n = nums.length;
|
||||
|
||||
// 定义target在左闭右闭的区间里,[low, high]
|
||||
int low = 0;
|
||||
int high = n - 1;
|
||||
|
||||
while (low <= high) { // 当low==high,区间[low, high]依然有效
|
||||
int mid = low + (high - low) / 2; // 防止溢出
|
||||
if (nums[mid] > target) {
|
||||
high = mid - 1; // target 在左区间,所以[low, mid - 1]
|
||||
} else if (nums[mid] < target) {
|
||||
low = mid + 1; // target 在右区间,所以[mid + 1, high]
|
||||
} else {
|
||||
// 1. 目标值等于数组中某一个元素 return mid;
|
||||
return mid;
|
||||
}
|
||||
}
|
||||
// 2.目标值在数组所有元素之前 3.目标值插入数组中 4.目标值在数组所有元素之后 return right + 1;
|
||||
return high + 1;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
Python:
|
||||
|
||||
|
Reference in New Issue
Block a user