zoukankan      html  css  js  c++  java
  • [容易]搜索插入位置

    题目来源:http://www.lintcode.com/zh-cn/problem/search-insert-position/

    C++版 VS2012测试通过

     1 //#include <iostream>
     2 //#include <vector>
     3 //using namespace std;
     4 
     5 class Solution {
     6     /** 
     7      * param A : an integer sorted array
     8      * param target :  an integer to be inserted
     9      * return : an integer
    10      */
    11 public:
    12     int searchInsert(vector<int> &A, int target) {
    13         // write your code here
    14         // find first position >= target
    15         if (A.size() == 0) {
    16             return 0;
    17         }     
    18         int start = 0, end = A.size() - 1;
    19         while (start + 1 < end) {
    20             int mid = (end - start) / 2 + start;
    21             if (A[mid] >= target) {
    22                 end = mid;
    23             } else {
    24                 start = mid;
    25             }
    26         }     
    27         if (A[start] >= target) {
    28             return start;
    29         }
    30         if (A[end] >= target) {
    31             return end;
    32         }       
    33         return A.size();
    34     }
    35 };
    36 
    37 //测试
    38 //int main()
    39 //{
    40 //    Solution s;
    41 //
    42 //    int a[]={0,3,5,6};
    43 //    vector<int> v(a,a+4);
    44 //
    45 //    int result=s.searchInsert(v,7);
    46 //    cout<<result;
    47 //}

    Python2.7版 spider测试通过

     1 class Solution:
     2     """
     3     @param A : a list of integers
     4     @param target : an integer to be inserted
     5     @return : an integer
     6     """
     7     def searchInsert(self, A, target):
     8         if len(A) == 0:
     9             return 0
    10         start, end = 0, len(A) - 1
    11         # first position >= target
    12         while start + 1 < end:
    13             mid = (start + end) / 2
    14             if A[mid] >= target:
    15                 end = mid
    16             else:
    17                 start = mid
    18 
    19         if A[start] >= target:
    20             return start
    21         if A[end] >= target:
    22             return end
    23         return len(A)
    24 
    25 #测试
    26 #if __name__=="__main__":
    27 #     s=Solution()
    28 #     L=[1,3,5,6]
    29 #     print s.searchInsert(L, 2)
  • 相关阅读:
    3.24课堂
    3.23作业
    3.23课堂
    3.20作业
    3.20课堂
    3.19作业
    3.19课堂
    3.18课堂
    3.18作业
    46、表与表的连接
  • 原文地址:https://www.cnblogs.com/hslzju/p/5605238.html
Copyright © 2011-2022 走看看