Search Insert Position @leetcode
生活随笔
收集整理的這篇文章主要介紹了
Search Insert Position @leetcode
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#二分我好亂
1 class Solution { 2 public: 3 int searchInsert(int A[], int n, int target) { 4 // IMPORTANT: Please reset any member data you declared, as 5 // the same Solution instance will be reused for each test case. 6 if(n == 0) return n; 7 if(target < A[0]) return 0; 8 else if(target > A[n-1]) return n; 9 else if(n == 2) 10 { 11 if(target == A[0]) return 0; 12 if(target <= A[1]) return 1; 13 } 14 int b,e; 15 b=0;e=n-1; 16 while(b+1<e) 17 { 18 if(A[b] == target) return b; 19 if(A[e] == target) return e; 20 if(A[(e+b)/2]>target) 21 e=(e+b)/2; 22 else if(A[(e+b)/2]<target) 23 b=(e+b)/2; 24 else 25 return (e+b)/2; 26 } 27 return e; 28 } 29 };#nb版
1 class Solution { 2 public: 3 int searchInsert(int A[], int n, int target) { 4 // IMPORTANT: Please reset any member data you declared, as 5 // the same Solution instance will be reused for each test case. 6 int left = 0, right = n; 7 int mid = 0; 8 while (left < right) { 9 mid = left + (right - left) / 2; 10 if (A[mid] > target) { 11 right = mid; 12 } else if (A[mid] < target) { 13 left = mid + 1; 14 } else { 15 return mid; 16 } 17 } 18 return left; 19 } 20 };?
?
轉載于:https://www.cnblogs.com/rogarlee/p/3423758.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的Search Insert Position @leetcode的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2013.11.13
- 下一篇: windows ce 5.0 + vs2