zoukankan      html  css  js  c++  java
  • 35. Search Insert Position

    class Solution {
        public int searchInsert(int[] nums, int target) {
            int n = nums.length;
            for(int i = 0; i< n; i++){
                if(nums[n-1]<target)
                    return n;
                else if(nums[i]>=target)
                    return i;
                
                           
            }
            return 0;        
        }
    }
    别人的答案:
    public int searchInsert(int[] nums, int target){
    int i = 0;
    for(int j = 0; j < nums.length; j++){
    if(nums[i] < target){
    i++;
    }
    }
    return i;
    }
    二分法:
    public class Solution {
    public int searchInsert(int[] nums, int target) {
        int low = 0, high = nums.length;
        while(low < high) {
            int mid = low + (high - low) / 2;
            if(nums[mid] < target)
                low = mid + 1;
            else
                high = mid;
        }
        return low;
    }
    总结:看到别人的方法真的恍然大悟,做题不应该有想法就动笔,应该再思考思考的,有时候一些很小的令感就可以省下很多行代码 然后就是,有序数组的查找应该首先想到二分查找。
  • 相关阅读:
    基于bootstrap分页
    encache学习教程
    java异常和spring事务注解
    JSP自定义标签开发入门
    spring junit
    vs与数据库连接查询
    winfrom文本文档打开
    面向对象 封装
    面向对象 概念
    DW 游记代码
  • 原文地址:https://www.cnblogs.com/ZoHy/p/12400681.html
Copyright © 2011-2022 走看看