码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:35. Search Insert Position

时间:2017-02-06 13:14:39      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:nbsp   []   system   log   todo   duplicate   bsp   oid   color   

 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

标签:nbsp   []   system   log   todo   duplicate   bsp   oid   color   

原文地址:http://www.cnblogs.com/luluqiao/p/6369653.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!