zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    多态性与转型
    安装tensorflow
    MySQL基础补缺
    各种排序算法理解
    Ubuntu命令行变成白色
    开机显示grub命令
    E: 无法获得锁 /var/lib/dpkg/lock-frontend
    类与方法
    Java语言浅谈
    二进制数的有效讨论
  • 原文地址:https://www.cnblogs.com/rogarlee/p/3423758.html
Copyright © 2011-2022 走看看