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 }

      

  • 相关阅读:
    内存条的物理结构分析【转载】
    JDK动态代理[2]----动态代理设计模式(文章转载于别处)
    shell 计算
    如何使用Vagrant创建linux环境(MacOS版)
    JavaFreemarker01快速上手
    7、验证信息
    6、更新文档
    5、删除文档
    4、查询文档02
    3、查询文档01
  • 原文地址:https://www.cnblogs.com/dreamrun/p/4521710.html
Copyright © 2011-2022 走看看