插入位置

    xiaoxiao2023-03-24  4

    问题:给定一个有序数组和一个目标值,返回目标值的下标,如果目标值不在输在里,那么返回其插入数组后的下标,插入后数组依然保持有序。假定数组不存在重复元素。

    依然采用二分查找,找到则返回下标

    没有找到,循环结束后,低位记录了第一个大于目标值的元素位置。即插入目标位置。

    // // SearchInsert.h // Algorithm // // Created by han shuai on 2016/9/27. // Copyright © 2016年 han shuai. All rights reserved. // /** 23 */ #import <Foundation/Foundation.h> @interface SearchInsert : NSObject - (NSInteger)searchInsert:(NSArray *)a target:(int)target; @end // // SearchInsert.m // Algorithm // // Created by han shuai on 2016/9/27. // Copyright © 2016年 han shuai. All rights reserved. // #import "SearchInsert.h" @implementation SearchInsert - (NSInteger)searchInsert:(NSArray *)a target:(int)target { NSInteger left = 0; NSInteger right = a.count -1; while (left <= right) { NSInteger mid = (left+right)/2; if ([a[mid] intValue] == target) { return mid; } else if ([a[mid] intValue] > target) { right = mid-1; } else { //低位靠近目标值 left = mid+1; } } return left; } @end

    转载请注明原文地址: https://ju.6miu.com/read-1201597.html
    最新回复(0)