35. Search Insert Position

来源:互联网 发布:js字符串比较相等 编辑:程序博客网 时间:2024/05/17 14:27
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);        }    }