LintCode: 二分查找
2018-03-25 12:59
471 查看
题目:
给定一个排序的整数数组(升序)和一个要查找的整数
样例
在数组
给定一个排序的整数数组(升序)和一个要查找的整数
target,用
O(logn)的时间查找到target第一次出现的下标(从0开始),如果target不存在于数组中,返回
-1。
样例
在数组
[1, 2, 3, 3, 4, 5, 10]中二分查找
3,返回
2。代码:
public int binarySearch(int[] nums, int target) { if (nums == null || nums.length == 0) { return -1; } // write your code here int pre = 0, end = nums.length-1; while(pre<end){ int middle = (pre+end)/2; if(nums[middle]<target){ pre = middle+1; }else if(nums[middle]>target){ end = middle-1; }else{ end = middle; // 这一步很重要,需要求的是第一次出现的下标 } } if(nums[pre]==target){ return pre; } return -1; }
相关文章推荐
- lintcode:二分查找
- LINTCODE---排序列表转换为二分查找树
- LintCode Binary Search 二分查找
- LintCode 二分查找
- lintcode- 题106 排序链表转换为二分查找树
- LintCode-二分查找
- LintCode-排序列表转换为二分查找树分析及实例
- lintcode-排序列表转换为二分查找树-106
- lintcode 容易题:Binary Search 二分查找
- Lintcode 14. 二分查找
- lintcode:二分查找
- LintCode python 小白-简单题-457经典二分查找问题
- LintCode-排序列表转换为二分查找树
- 一起lintcode ------- 二分查找看这篇就够了
- LintCode : 二分查找
- lintCode_二分查找
- Vasya and String CodeForces - 676C [二分查找 + 尺取法]
- Lintcode---单词的添加与查找
- LintCode : 字符串查找
- codeforces G. Doctor(二分查找)