在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Given a sorted array of integers, find the starting and ending position of a given target value. 1 public static List<int> SearchforaRange(int[] A, int target) 2 { 3 List<int> ret = new List<int>(); 4 5 ret.Add(BinarySearchlow(A, 0, A.Length - 1, target)); 6 ret.Add(BinarySearchup(A, 0, A.Length - 1, target)); 7 8 return ret; 9 } 10 11 public static int BinarySearchlow(int[] A, int start, int end, int target) 12 { 13 if (start > end) 14 return -1; 15 16 int mid = start + ((end - start) / 2); 17 if(A[mid] == target && (mid == 0 || A[mid - 1] < target)) 18 { 19 return mid; 20 } 21 else if (A[mid] < target) 22 { 23 return BinarySearchlow(A, mid + 1, end, target); 24 } 25 else 26 { 27 return BinarySearchlow(A, start, mid - 1, target); 28 } 29 } 30 31 public static int BinarySearchup(int[] A, int start, int end, int target) 32 { 33 if (start > end) 34 return -1; 35 36 int mid = start + ((end - start) / 2); 37 if (A[mid] == target && (mid == end || A[mid + 1] > target)) 38 { 39 return mid; 40 } 41 else if (A[mid] > target) 42 { 43 return BinarySearchup(A, start, mid - 1, target); 44 } 45 else 46 { 47 return BinarySearchup(A, mid + 1, end, target); 48 } 49 } 代码分析: 时间复杂度要求O(log n),已经提醒了要用二分查找法,这个其实就是一个Binary Search 的 Variant。 |
请发表评论