LeetCode Online Judge 题目C# 练习 - Search for a Range
2012-10-16 22:47
731 查看
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 [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
代码分析:
时间复杂度要求O(log n),已经提醒了要用二分查找法,这个其实就是一个Binary Search 的 Variant。
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].
public static List<int> SearchforaRange(int[] A, int target) { List<int> ret = new List<int>(); ret.Add(BinarySearchlow(A, 0, A.Length - 1, target)); ret.Add(BinarySearchup(A, 0, A.Length - 1, target)); return ret; } public static int BinarySearchlow(int[] A, int start, int end, int target) { if (start > end) return -1; int mid = start + ((end - start) / 2); if(A[mid] == target && (mid == 0 || A[mid - 1] < target)) { return mid; } else if (A[mid] < target) { return BinarySearchlow(A, mid + 1, end, target); } else { return BinarySearchlow(A, start, mid - 1, target); } } public static int BinarySearchup(int[] A, int start, int end, int target) { if (start > end) return -1; int mid = start + ((end - start) / 2); if (A[mid] == target && (mid == end || A[mid + 1] > target)) { return mid; } else if (A[mid] > target) { return BinarySearchup(A, start, mid - 1, target); } else { return BinarySearchup(A, mid + 1, end, target); } }
代码分析:
时间复杂度要求O(log n),已经提醒了要用二分查找法,这个其实就是一个Binary Search 的 Variant。
相关文章推荐
- LeetCode Online Judge 题目C# 练习 - Search a 2D Matrix
- LeetCode Online Judge 题目C# 练习 - Unique Binary Search Trees
- LeetCode Online Judge 题目C# 练习 - Search in Rotated Sorted Array
- LeetCode Online Judge 题目C# 练习 - Search in Rotated Sorted Array II
- LeetCode Online Judge 题目C# 练习 - Roman to Integer
- LeetCode Online Judge 题目C# 练习 - Search Insert Position
- LeetCode Online Judge 题目C# 练习 - Rotate List
- LeetCode Online Judge 题目C# 练习 - Container With Most Water
- LeetCode Online Judge 题目C# 练习 - Simplify Path
- LeetCode Online Judge 题目C# 练习 - Sqrt(x)
- LeetCode Online Judge 题目C# 练习 - Multiply Strings
- LeetCode Online Judge 题目C# 练习 - Palindrome Number
- LeetCode Online Judge 题目C# 练习 - Remove Nth Node From End of List
- LeetCode Online Judge 题目C# 练习 - Letter Combinations of a Phone Number
- LeetCode Online Judge 题目C# 练习 - Longest Valid Parentheses
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted List II
- LeetCode Online Judge 题目C# 练习 - Longest Common Prefix
- leetcode做题总结,题目Search for a Range 2012/03/02
- LeetCode Online Judge 题目C# 练习 - Sort Color
- LeetCode Online Judge 题目C# 练习 - Unique Binary Search Trees II