您的位置:首页 > 编程语言 > C#

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].

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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: