LeetCode:35. Search Insert Position
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:35. Search Insert Position相关的知识,希望对你有一定的参考价值。
1 package Today; 2 //LeetCode:35. Search Insert Position 3 /* 4 Given a sorted array and a target value, return the index if the target is found. 5 If not, return the index where it would be if it were inserted in order. 6 7 You may assume no duplicates in the array. 8 9 Here are few examples. 10 [1,3,5,6], 5 → 2 11 [1,3,5,6], 2 → 1 12 [1,3,5,6], 7 → 4 13 [1,3,5,6], 0 → 0 14 */ 15 public class searchInsert35 { 16 public static int searchInsert(int[] nums, int target) { 17 for(int i=0;i<nums.length;i++){ 18 if(nums[i]>=target) 19 return i; 20 } 21 return nums.length; 22 } 23 //study 写的磕磕巴巴的 24 public static int searchInsert2(int[] nums,int target){ 25 int left=0,right=nums.length; 26 while(left<right){ 27 int mid=(left+right)/2; 28 if(nums[mid]==target) 29 return mid; 30 else if(nums[mid]<target) 31 left=mid+1; 32 else 33 right=mid; 34 } 35 return left; 36 } 37 public static void main(String[] args) { 38 // TODO Auto-generated method stub 39 int[] nums={1,3,5,6}; 40 System.out.println(searchInsert(nums,5)); 41 System.out.println(searchInsert(nums,2)); 42 System.out.println(searchInsert(nums,7)); 43 System.out.println(searchInsert(nums,0)); 44 45 46 System.out.println(searchInsert2(nums,5)); 47 System.out.println(searchInsert2(nums,2)); 48 System.out.println(searchInsert2(nums,7)); 49 System.out.println(searchInsert2(nums,0)); 50 } 51 52 }
以上是关于LeetCode:35. Search Insert Position的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 35. Search Insert Position
[Binary Search] Leetcode 35, 74
[LeetCode]35. Search Insert Position
Leetcode-35 Search Insert Position