public class Solution
    {
        public int Search(int[] nums, int target)
        {
            var len = nums.Length;

            var low = 0;
            var high = len - 1;
            if (target == nums[low])
            {
                return low;
            }
            else if (target == nums[high])
            {
                return high;
            }
            while (low < high)
            {
                var mid = (low + high) / 2;
                var cur = nums[mid];

                if (target == cur)
                {
                    return mid;
                }
                else if (target < cur)
                {
                    high = mid - 1;
                }
                else
                {
                    low = mid + 1;
                }
            }
            return -1;
        }
    }

 

Java版本代码

 1 class Solution {
 2     public int search(int[] nums, int target) {
 3         int n = nums.length;
 4         int low = 0;
 5         int high = n - 1;
 6         while(low <= high){
 7             int mid = (low + high) / 2;
 8             int cur = nums[mid];
 9             if(cur == target){
10                 return mid;
11             }else if(cur < target){
12                 low = mid + 1;
13             }else{
14                 high = mid - 1;
15             }
16         }
17         return -1;
18     }
19 }

 

posted on 2018-10-01 14:29  Sempron2800+  阅读(106)  评论(0编辑  收藏  举报