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 };
  • 相关阅读:
    C#去掉数组中重复的字符串 .Distinct()
    文件上传 uploadlabs
    Sipdroid初尝
    腾讯面试小记
    C/C++拾遗(二)
    ZigBee简介
    大端小端
    字符串——算法系列
    重复定义
    C/C++拾遗
  • 原文地址:https://www.cnblogs.com/rogarlee/p/3423758.html
Copyright © 2011-2022 走看看