zoukankan      html  css  js  c++  java
  • leetcode之Search Insert Position2

    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

    首先想到用二分查找,因为满足在给定的有序数组中查找元素的位置。

    一遍编译通过,但是对return的用法不是很了解。

    下面附上我的代码,运行效率并不是很高。

     public int searchInsert(int[] A, int target) {
            int result = 0;
            int length = A.length;
            int low = 0;
            int high = length-1;
            while(low<high){
            	int mid = (high+low)/2;
            	if(A[mid]<target){
            		low = mid+1;
            	}
            	else{
            		if(A[mid]>target){
                		high = mid-1;
                	}
            		else{
            			result = mid;
            			return result;
            		}
            	} 
            }
            if(A[low]<target){
            	result = high + 1;
            	return result;
            }
            if(A[low]>target){
            	result = low;
            	return result;
            }
    		return low;
           
        }
    

      别人的代码如下:

    public static int searchInsert1(int[] A, int target) {
    		int result = 0;
    		int n = A.length;
    		int low = 0;
    		int high = n - 1;
    		while (low <= high) {
    			int mid = (low + high) >> 1;
    			if (A[mid] == target)
    				return mid;
    			else if (A[mid] > target)
    				high = mid - 1;
    			else
    				low = mid + 1;
    		}
    		if (high < 0)
    			return 0;
    		if (low >= n)
    			return n;
    		return low;
    	}
    

      

  • 相关阅读:
    oracle权限配置
    oracle锁表处理
    小组成员
    个人项目 Individual Project
    Java单元测试框架 JUnit
    MyEclipse的快捷键大全(超级实用,方便)
    vs2008 连接 vss2005 出现 analyze utility 错误的解决方法
    EXTJS gridpanel 动态设置表头
    IE8不能上网的问题
    一些事件的评论
  • 原文地址:https://www.cnblogs.com/gracyandjohn/p/4402786.html
Copyright © 2011-2022 走看看