码迷,mamicode.com
首页 > 其他好文 > 详细

search-insert-position

时间:2016-11-05 09:39:41      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:https   problems   tar   exce   pac   二分查找   turn   mock   any   

https://leetcode.com/problems/search-insert-position/

https://leetcode.com/mockinterview/session/result/xjw45dt/

这是一个典型的二分查找。注意一些坑。比如里面start end的设置,到了边界条件时+1 -1的处理等。

package com.company;


import java.util.*;

class Solution {
    public int searchInsert(int[] nums, int target) {
        int start = 0;
        int end = nums.length - 1;
        int mid;
        while (start <= end) {
            mid = start + (end - start) / 2;
            if (nums[mid] == target) {
                return mid;
            }
            else if (nums[mid] > target) {
                end = mid - 1;
            }
            else {
                start = mid + 1;
            }
        }
        return start;
    }
}

public class Main {

    public static void main(String[] args) throws InterruptedException {

        System.out.println("Hello!");
        Solution solution = new Solution();

        // Your Codec object will be instantiated and called as such:
        int[] nums = {1,3,5,6,7};
        int target = 7;
        int ret = solution.searchInsert(nums, target);
        System.out.printf("ret:%d\n", ret);

        System.out.println();

    }
}

 

search-insert-position

标签:https   problems   tar   exce   pac   二分查找   turn   mock   any   

原文地址:http://www.cnblogs.com/charlesblc/p/6032419.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!