zoukankan      html  css  js  c++  java
  • 35_Search Insert Position

    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

    在一个顺序数组中找某个值x的位置。若x存在该数组中,则返回x在该数组的位置i;若不存在,则把x按照顺序放进该数组并返回此时x的位置。

    顺序查找:

    int searchInsert(int* nums, int numsSize, int target) {
        int result = 0;
        for(int i = 0; i < numsSize; i++)
        {
            if(nums[i] == target)
            {
                result = i;
                break;
            }
            else if(nums[i] < target)
            {
                if(i < numsSize - 1)
                {
                    continue;
                }
                else
                {
                    result = i + 1;
                    break;
                }
            }
            else//target < nums[i]
            {
                result = i;
                break;
            }
        }
        
        return result;
    }

    由于该数组是顺序的,二分查找法可能速度更快

    二分查找:

    int searchInsert(int* nums, int numsSize, int target) {
        int cursor = 0;
        int low = 0;
        int high = numsSize - 1;
        
        if(low == high)
        {
            if(nums[0] >= target)
            {
                return 0;
            }
            else
            {
                return 1;
            }
        }
        
        while (low <= high)
        {
            cursor = (low + high) / 2;
            if(nums[cursor] == target)
            {
                return cursor;
            }
            else if(nums[cursor] > target)
            {
                high = cursor - 1;
                continue;
            }
            else
            {
                low = cursor + 1;
                continue;
            }
        }
        
        cursor = (low + high) / 2;
        
        if(nums[cursor] > target)
        {
            return cursor;
        }
        else
        {
            return cursor + 1;
        }
        
    }
  • 相关阅读:
    高效管理,经理人须熟练运用的几个工具
    投资感情 收获人心
    忽如一夜入冬来
    贺嫦娥奔月
    正确处理人际关系,给自己做无形的投资
    观南溪豆干有感
    身在职场,请善待你的每一张白纸
    游一品天下有感
    增强影响力,如何提升你的“领袖气质”?
    oracle 创建表空间
  • 原文地址:https://www.cnblogs.com/Anthony-Wang/p/5276419.html
Copyright © 2011-2022 走看看