
文章目录
问题
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7]
可能变为 [4,5,6,7,0,1,2]
)。
搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1
。
你可以假设数组中不存在重复的元素。
你的算法时间复杂度必须是 O(log n) 级别。
输入: nums = [4,5,6,7,0,1,2], target = 0
输出: 4
输入: nums = [4,5,6,7,0,1,2], target = 3
输出: -1
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7]
might become [4,5,6,7,0,1,2]
).
You are given a target value to search. If found in the array return its index, otherwise return -1
.
You may assume no duplicate exists in the array.
Your algorithm’s runtime complexity must be in the order of O(log n).
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
示例
public class Program { public static void Main(string[] args) { int[] nums = { 2, 7, 11, 15 }; var res = TwoSum(nums, 9); var res2 = TwoSum2(nums, 9); Console.WriteLine($"[{res[0]},{res[1]}]"); Console.WriteLine($"[{res2[0]},{res2[1]}]"); Console.ReadKey(); } public static int[] TwoSum(int[] nums, int target) { //类似于冒泡,双循环比较2个数的和与目标值是否相等 for (int i = 0; i < nums.Length; i++) { for (int j = i + 1; j < nums.Length; j++) { if (nums[i] + nums[j] == target) { return new int[] { i, j }; } } } //找不到时抛出异常 throw new ArgumentException(); } public static int[] TwoSum2(int[] nums, int target) { //用数组中的值做key,索引做value存下所有值 var dictionary = new Dictionary<int, int>(); for (int i = 0; i < nums.Length; i++) { //记录差值 int complement = target - nums[i]; //若字典中已经存在这个值,说明匹配成功 if (dictionary.ContainsKey(complement)) { return new int[] { dictionary[complement], i }; } //记录索引 dictionary[nums[i]] = i; } //找不到时抛出异常 throw new ArgumentException(); } }
以上给出2种算法实现,以下是这个案例的输出结果:
[0,1] [0,1]
分析
显而易见,TwoSum 的时间复杂度为: ,TwoSum2 的时间复杂度为:
。
本文由 .Net中文网 原创发布,欢迎大家踊跃转载。
转载请注明本文地址:https://www.byteflying.com/archives/4968。