zoukankan      html  css  js  c++  java
  • [LeetCode]Search Insert Position

    称号:给定的一组数字。集数字上升。给定一个数字target,获取数字target放置在集合索引值(同样升序)

    算法:一个简单的比较

    public class Solution {
        public int searchInsert(int[] A, int target) {
    	        int i = 0;
    	    	for (; i<A.length; ++i) {
    	        	if (target <= A[i]) {
    	        		break;
    	        	}
    	        }
    	    	return i;
    	    }
    }

    算法:二分查找

    原理:集合数字有序,依据二分查找可不断缩小target在集合中的范围

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

    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    【JavaScript】函数(未完全)
    Spring集成Jersey开发(附demo)
    Tomcat中work目录的作用
    Lucene全文检索(一)
    JS放大镜特效(兼容版)
    S2SH整合
    EL表达式
    JSP和JavaBean
    Cookie和Session
    request对象和response对象
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/4639101.html
Copyright © 2011-2022 走看看