LeetCode Online Judge 题目C# 练习 - Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

 1         public static int SearchInsertPosition(int[] A, int target)
 2         {
 3             return BSSearchInsertPosision(A, 0, A.Length - 1, target);
 4         }
 5 
 6         public static int BSSearchInsertPosision(int[] A, int start, int end, int target)
 7         {
 8             if (start > end)
 9                 return start;
10 
11             int mid = start + (end - start) / 2;
12             if (A[mid] == target)
13                 return mid;
14             else if (A[mid] < target)
15                 return BSSearchInsertPosision(A, mid + 1, end, target);
16             else
17                 return BSSearchInsertPosision(A, start, mid - 1, target);
18         }

代码分析:

  同样,Binary Search 的变体,如果start > end (找不到)返回start。 能涵盖所有case 了。

posted @ 2012-10-17 00:08  ETCOW  阅读(272)  评论(0编辑  收藏  举报