zoukankan      html  css  js  c++  java
  • 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

     解题一:

    二分法查找

    public class Solution {
    public int searchInsert(int[] array, int value) {
    int high = array.length - 1;
    int low = 0,flag = 0;
    while(low <= high)
    {
    int middle = (low + high) / 2;
    if(value == array[middle])
    {
    flag = 1;
    return middle;
    }
    if(value > array[middle])
    {
    low = middle + 1;
    }
    if(value < array[middle])
    {
    high = middle - 1;
    }
    }
    if(flag == 0)
    return low;
    return -1;
    }
    }

    public class Solution {
        public int searchInsert(int[] array, int value) {
            int high = array.length - 1;
            int low = 0,flag = 0;
            while(low <= high)
            {
                int middle = (low + high) / 2;
                if(value == array[middle])
                {
                    flag = 1;
                    return middle;
                }
                if(value > array[middle])
                {
                    low = middle + 1;
                }
                if(value < array[middle])
                {
                    high = middle - 1;
                }
            }
            if(flag == 0)
                return low;
            return -1;
        }
    }
    

      

  • 相关阅读:
    修改 dll
    SQLServer中char、varchar、nchar、nvarchar的区别:
    关于破解的一点心得
    asp.net 操作XML
    jquery autocomplete
    【转】height,posHeight和pixelHeight区别
    异常处理 Access to the path is denied
    asp.net 获得客户端 mac 地址
    cmd 跟踪路由
    Excel 宏
  • 原文地址:https://www.cnblogs.com/xww115/p/11230447.html
Copyright © 2011-2022 走看看