public class Solution { public int SearchInsert(int[] nums, int target) { if (nums.Contains(target)) { return Array.IndexOf(nums, target); } else { return zhong(nums,0,nums.Length-1,target); } } private int zhong(int[] ss,int start,int end,int target) { if (target < ss[end] && target > ss[start]) { if (ss[(int)((start + end) / 2)] < target && target < ss[(int)((start + end) / 2) + 1]) { return (int)((start + end) / 2) + 1; } else { if(ss[(int)((start + end) / 2)] > target) { return zhong(ss, start, (int)((start + end) / 2),target); } else { return zhong(ss, (int)((start + end) / 2),end , target); } } } else { if (target < ss[start]) { return start; } else { return end+1; } } } }
//又一版二分法 public int half(int[] nums,int target,int start,int end){ if(nums.Length==0){ return 0; } else if(nums[0]>=target){ return 0; } else if(nums[nums.Length-1]<=target){ return nums.Length; } else{ if(nums[(start+end)/2]<=target){ if(nums[(start+end)/2+1]>=target){ return (start+end)/2+1; } else{ return half(nums,target,(start+end)/2,end); } } else{ if((start+end)/2-1<0){ return 0; } else{ if(nums[(start+end)/2-1]<=target){ return (start+end)/2; } else{ return half(nums,target,start,(start+end)/2); } } } } } }
C#代码,望大神指正