# C#LeetCode刷题之#33-搜索旋转排序数组（Search in Rotated Sorted Array）

## 问题

( 例如，数组 `[0,1,2,4,5,6,7]` 可能变为 `[4,5,6,7,0,1,2]` )。

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]}]");

}

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();
}

}```

```[0,1]
[0,1]```