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;
    	}
    

      

  • 相关阅读:
    【面积并】 Atlantis
    【动态前k大 贪心】 Gone Fishing
    【复杂枚举】 library
    【双端队列bfs 网格图建图】拯救大兵瑞恩
    【奇偶传递关系 边带权】 奇偶游戏
    【权值并查集】 supermarket
    CF w4d3 A. Pythagorean Theorem II
    CF w4d2 C. Purification
    CF w4d2 B. Road Construction
    CF w4d2 A. Cakeminator
  • 原文地址:https://www.cnblogs.com/gracyandjohn/p/4402786.html
Copyright © 2011-2022 走看看