首页 > 代码库 > LeetCode:35. Search Insert Position
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。