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], 52
[1,3,5,6], 21
[1,3,5,6], 74
[1,3,5,6], 00 

给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。
你可以假设在数组中无重复元素。

程序:

public class SearchInsertSolution
    {
        //线性搜索168ms
        public static int SearchInsert(int[] nums, int target)
        {
            for (int i = 0; i < nums.Length; i++)
                if (target <= nums[i]) return i;
            return nums.Length;
        }

        //二分查找 156ms
        public static int SearchInsertBinary(int[] nums, int target)
        {
            int low = 0;
            int high = nums.Length - 1;
            int mid = high / 2;
            while (high != low)
            {
                if (target == nums[mid]) return mid;
                else if (target < nums[mid])
                {
                    high = mid;
                    mid = (high - low) / 2 + low;
                }
                else
                {
                    low = mid + 1;
                    mid = (high - low) / 2 + low;
                }
            }
            return target > nums[high] ? high + 1 : high;
        }
    }

单元测试(通过):

[TestClass]
    public class UnitTest35_SearchInsertPosition
    {
        [TestMethod]
        public void TestMethodSearchInsert()
        {
            var arr1 = new int[] { 1 };
            var res = SearchInsertSolution.SearchInsert(arr1, 0);
            Assert.AreEqual(0, res);
        }

        [TestMethod]
        public void TestMethodSearchInseartBinary()
        {
            var arr1 = new int[] { 1 };
            var res1 = SearchInsertSolution.SearchInsertBinary(arr1, 0);
            var res2 = SearchInsertSolution.SearchInsertBinary(arr1, 2);
            Assert.AreEqual(0, res1);
            Assert.AreEqual(1, res2);
            var arr2 = new int[] { 1, 3, 5, 7 };
            var res3 = SearchInsertSolution.SearchInsertBinary(arr2, 0);
            Assert.AreEqual(0, res3);
            var res4 = SearchInsertSolution.SearchInsertBinary(arr2, 3);
            Assert.AreEqual(1, res4);
            var res5 = SearchInsertSolution.SearchInsertBinary(arr2, 4);
            Assert.AreEqual(2, res5);
            var res6 = SearchInsertSolution.SearchInsertBinary(arr2, 8);
            Assert.AreEqual(4, res6);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值