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

  

posted @ 2015-04-08 16:28  niuer++  阅读(149)  评论(0编辑  收藏  举报