- Search Insert Position
Easy
2743266Add to ListShare
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2:
Input: nums = [1,3,5,6], target = 2
Output: 1
Example 3:
Input: nums = [1,3,5,6], target = 7
Output: 4
Example 4:
Input: nums = [1,3,5,6], target = 0
Output: 0
Example 5:
Input: nums = [1], target = 0
Output: 0
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums
contains distinct values sorted in ascending order.-104 <= target <= 104
解决思路
-
利用Java自带的库函数
a. 利用contains 判断数组是否包含数字
b. 如果包含, 则返回索引
c. 不包含, 则循环遍历
-
利用Java自带的Stream进行遍历
-
二分搜索
部分代码
class Solution { public int searchInsert(int[] nums, int target) { int l = 0, r = nums.length - 1; if (nums[r] < target) { return nums.length; } while (l < r) { int mid = (l + r) / 2; if (nums[mid] >= target) { r = mid; } else { l = mid + 1; } } return l; } }
全部代码
package Easy.sangshiwu; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; class Solution { public int searchInsert(int[] nums, int target) { int l = 0, r = nums.length - 1; // if (nums[r] < target) { // return nums.length; // } if (nums[l] >= target) { return 0; } while (l < r) { int mid = (l + r) / 2; if (nums[mid] >= target) { r = mid; } else { l = mid + 1; } } return l; // return Arrays.stream(nums) // .forEach( ); // if(Arrays.stream(nums)) } private boolean checked(int value, int target) { return false; } } public class MainClass { public static void main(String[] args) throws IOException { int res = new Solution().searchInsert(new int[]{1, 3, 5, 6}, 5); System.out.println(res); // BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // String line; // while ((line = in.readLine()) != null) { // int[] nums = line.to // int ret = new Solution().searchInsertan); // String out = String.valueOf(ret); // System.out.print(out); // } } }