Lintcode二分搜索

来源:互联网 发布:大数据的盈利模式 编辑:程序博客网 时间:2024/05/01 03:57
Problem Statement

For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time complexity.

If the target number does not exist in the array, return -1.

Example

If the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.

Challenge

If the count of numbers is bigger than 2^{32}232, can your code work properly?

使用二分搜索时应满足:数组必须已经排序,时间复杂度是O(logn)

/*For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time complexity.If the target number does not exist in the array, return -1.ExampleIf the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.ChallengeIf the count of numbers is bigger than 2^{32}2​32​​, can your code work properly? */public class Main {public static void main(String[] args) {int[] a = new int[] { 1, 2, 3, 3, 4, 5, 10 };System.out.println(binarySearch(a, 3));}private static int binarySearch(int[] arr, int target) {int left = 0;int right = arr.length - 1;int mid = (left + right) / 2;while (left < right) {if (arr[mid] > target) {right = mid;} else if (arr[mid] < target) {left = mid;} else {return mid;}mid = (left + right) / 2;}return -1;}}


0 0
原创粉丝点击