zoukankan      html  css  js  c++  java
  • Search Insert Position

    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.

    思路:

    二分查找问题

    我的代码:

    public class Solution {
        public int searchInsert(int[] A, int target) {
            if( A == null || A.length == 0) return -1;
            int left = 0;
            int right = A.length - 1;
            while(left <= right)
            {
                int mid = (left + right)/2;
                if(A[mid] == target)    return mid;
                else if(A[mid] > target)    right = mid - 1;
                else left = mid + 1;
            }
            return left;
        }
    }
    View Code

    学习之处:

    • 二分查找left≤right
    • 二分查找停止循环时候的left和right的位置 想想真是公平哒,刚开始left < right,退出循环的话,left指向大的数据,right指向小的数据

    if(null==nums || nums.length==0) return -1;
    int left = 0;
    int right = nums.length - 1;

    while(left <= right){
    int mid = (left+right)/2;
    if(target == nums[mid]) return mid;
    if(target > nums[mid]) left = mid+1;
    if(target < nums[mid]) right = mid-1;
    }

    return left;

  • 相关阅读:
    memset使用技巧
    04.碰撞反应
    03.键盘状态跟踪与精灵删除
    02.基本动作
    01.基本图形
    00.入门
    03.交互--鼠标,键盘
    02.action--新增精灵知识点
    01.helloworld--标签
    05.声音
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4313581.html
Copyright © 2011-2022 走看看