34. Search for a Range
2016-02-22 06:46
411 查看
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return
For example,
Given
return
Solution 1 Find the leftmost and rightmost bound using binary search
Solution 2 Recursive
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return
[-1, -1].
For example,
Given
[5, 7, 7, 8, 8, 10]and target value 8,
return
[3, 4].
Solution 1 Find the leftmost and rightmost bound using binary search
public static int[] searchRange(int[] nums, int target) { int start = 0; int end = nums.length - 1; int range [] = {-1, -1}; while(start < end){ int mid = (start + end) / 2; if(target > nums[mid]){ start = mid + 1; }else{ end = mid; } } if(nums[start] != target){ return range; }else{ range[0] = start; } end = nums.length - 1; while(start < end){ int mid = (start + end) / 2 + 1; if(nums[mid] > target){ end = mid - 1; }else{ start = mid; } } range[1] = end; return range; }
Solution 2 Recursive
public static int[] searchRange2(int[] nums, int target) { int [] range = {Integer.MAX_VALUE, -1}; searchRange(nums, target, 0, nums.length - 1, range); if(range[0] > range[1]){ range[0] = -1; } return range; } public static void searchRange(int [] nums, int target, int left, int right, int [] range){ if(left > right){ return; } int mid = (left + right) / 2; if(nums[mid] == target){ if(mid < range[0]){ range[0] = mid; searchRange(nums, target, left, mid - 1, range); } if(mid > range[1]){ range[1] = mid; searchRange(nums, target, mid + 1, right, range); } }else if(nums[mid] < target){ searchRange(nums, target, mid + 1, right, range); }else{ searchRange(nums, target, left, mid - 1, range); } }
相关文章推荐
- Integer的源码分析
- MVC Controller return 格式之JsonResult、ContentResult、RedirectResult……
- iOS中的两种搜索方式UISearchDisplayController和UISearchController
- iOS中的两种搜索方式UISearchDisplayController和UISearchController
- iOS中的两种搜索方式UISearchDisplayController和UISearchController
- HashMap 分析
- 81. Search in Rotated Sorted Array II
- 51Nod 1013 3的幂的和(快速幂+逆元)
- LeetCode Binary Tree Upside Down
- 【Leetcode】House Robber II
- [Immutable.js] Converting Immutable.js Structures to Javascript and other Immutable Types
- Linux发展史
- 怎样的学术导师是好导师(Nature)
- 【Android】11.6 Fragments基本用法示例
- 【NYOJ】[268]荷兰国旗问题
- [Immutable.js] Transforming Immutable Data with Reduce
- 【Android】11.5 创建和管理Fragments
- 按首字母分类并排序显示的列表(二)--给BaseExpandableListAdapter提供数据的HashList
- 【Android】11.4 Fragment及其生命周期
- uva 10277 Boastin' Red Socks