zoukankan      html  css  js  c++  java
  • No.35 Search Insert Position

    No.35 Search Insert Position

    Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

    You may assume no duplicates in the array.

    Here are few examples.
    [1,3,5,6], 5 → 2
    [1,3,5,6], 2 → 1
    [1,3,5,6], 7 → 4
    [1,3,5,6], 0 → 0


     1 #include "stdafx.h"
     2 #include <vector>
     3 #include <iostream>
     4 using namespace std;
     5 
     6 class Solution
     7 {
     8 public:
     9     int searchInsert(vector<int> & numbers, int target)
    10     {//典型的二分查找
    11      //输入:数组numbers(无重复元素),target待查找的元素
    12      //输出:若target在numbers中,则输出其下标(从0开始);否则,输出若target插入数组,在数组中的下标
    13         
    14         //判断是否可查,即数组是否为空
    15         if(numbers.size() == 0)
    16             return 0;//此时若插入,下标为0
    17         int low = 0;
    18         int height = numbers.size()-1;
    19         int middle;
    20 
    21         while(low <= height)
    22         {
    23             middle = (low+height)/2;
    24             if(numbers[middle] == target)
    25                 return middle;
    26             else
    27                 if(numbers[middle] < target)
    28                     low = middle + 1;
    29                 else
    30                     height = middle - 1;
    31         }
    32         if(low != height)
    33             return (low > height ? low : height);
    34         //return low;
    35         //当循环结束时,如果没有找到目标元素,那么low一定停在恰好比目标大的index上,height一定停在恰好比目标小的index上
    36     }
    37 };
    38 
    39 int main()
    40 {
    41     Solution sol;
    42     int data[] = {1,3,5,6};
    43     vector<int> test(data,data+sizeof(data)/sizeof(int));
    44 
    45     cout <<"5 -> "<< sol.searchInsert(test, 5)<< endl;
    46     cout <<"2 -> "<< sol.searchInsert(test, 2)<< endl;
    47     cout <<"7 -> "<< sol.searchInsert(test, 7)<< endl;
    48     cout <<"0 -> "<< sol.searchInsert(test, 0)<< endl;
    49 }

      

  • 相关阅读:
    从开发人员角度对软件测试的些许理解
    ObjectiveC的语法
    HttpModule与HttpHandler使用
    我为什么学习HASKELL?
    Linux下C语言编程环境Make命令和Makefile
    一个简单的验证框架
    程序员之路
    ObjectiveC语法之ObjectiveC语言和IOS系统(简介,语法,系统结构)
    Teamcity
    Python进阶 错误处理
  • 原文地址:https://www.cnblogs.com/dreamrun/p/4521710.html
Copyright © 2011-2022 走看看