代码改变世界

LeetCode FindMinimuminRotatedSorteArray &&FindMinimuminRotatedSorteArray2

2015-05-19 10:52  F_Code  阅读(190)  评论(0编辑  收藏  举报

LeetCode上这两道题主要是使用二分搜索解决,是二分搜索算法的一个应用,根据条件每次舍弃一半,保留一半。

首先第一题: FindMinimuminRotatedSorteArray(时间复杂度为二分算法的时间复杂度O(logN))

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace Leetcode
 8 {
 9     public class FindMinimuminRotatedSorteArray
10     {
11         public int FindMin(int[] nums)
12         {
13             int length = nums.Length;
14             int beg = 0;
15             int end = length - 1;//闭区间,注意-1
16             int mid = 0;
17             while (beg < end)
18             {
19                 if (nums[beg] < nums[end])//如果成立代表数组是有序的,直接退出循环
20                     break;
21                 mid = (beg + end) / 2;
22                 if (nums[beg] > nums[mid])//这里面将两个元素的特殊情况包括在内
23                 {
24                     end = mid;
25                 }
26                 else
27                 {
28                     beg = mid + 1;
29                 }
30             }
31             return nums[beg];
32         }
33     }
34 
35     /*参考博客地址:http://blog.csdn.net/loverooney/article/details/40921751*/
36 }

第二题由于存在重复元素,无法判定每次舍弃哪一半,故需要一次一次的判断,时间复杂度为O(n)

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace Leetcode
 8 {
 9     class FindMinimuminRotatedSorteArray2
10     {
11         public int FindMin(int[] nums)
12         {
13             int length = nums.Length;
14             int beg = 0;
15             int end = length - 1;
16             int mid = 0;
17             while (beg < end)
18             {
19                 if (nums[beg] < nums[end])
20                     break;  
21                 mid = (beg + end) / 2;
22                 if (nums[beg] > nums[mid])
23                 {
24                     end = mid;//闭区间(也有可能mid是最小值)
25                 }
26                 else if (nums[mid] > nums[end])
27                 {
28                     beg = mid + 1;//开区间,因此+1(mid不可能是最小值)
29                 }
30                 else//这种情况是nums[beg]=nums[mid]=nums[end],因为此时nums[end]<nums[beg]
31                 {
32                     beg++;
33                 }
34             }
35             return nums[beg];
36         }
37     }
38 }