Algorithms—33.Search in Rotated Sorted Array

原创 2015年07月07日 17:56:31

思路:没什么好的思路,分各种情况讨论。

public class Solution {
    public int search(int[] nums, int target) {
		if (nums.length==1) {
			if (nums[0]==target) {
				return 0;
			}else {
				return -1;
			}
		}
		int begin=0;
		int end=nums.length-1;
		int half=(end+begin)/2;
		while (end-begin>1) {
			int b=nums[begin];
			int h=nums[half];
			int e=nums[end];
			if (h==target) {
				return half;
			}
			if (b==target) {
				return begin;
			}
			if (e==target) {
				return end;
			}
			if (h>b) {
				if (target>h) {
					begin=half;
					half=(end+begin)/2;
				}else {
					if (target>b) {
						end=half;
						half=(end+begin)/2;
					}else {
						begin=half;
						half=(end+begin)/2;
					}
				}
			}else {
				if (target<h) {
					end=half;
					half=(end+begin)/2;
				}else {
					if (target>e) {
						end=half;
						half=(end+begin)/2;
					}else {
						begin=half;
						half=(end+begin)/2;
					}
				}
			}
		}
		if (nums[begin]==target) {
			return begin;
		}
		if (nums[end]==target) {
			return end;
		}

		return -1;
	}
}


耗时:316ms。中上游,大部分测试情况都是靠系统,考虑不周全。


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode Algorithms 33. Search in Rotated Sorted Array

题目难度: Medium 原题描述: Suppose an array sorted in ascending order is rotated at some pivot unk...

LeetCode 33 — Search in Rotated Sorted Array(C++ Java Python)

题目:http://oj.leetcode.com/problems/search-in-rotated-sorted-array/ Suppose a sorted array is rotate...

leetcode(33). Search in Rotated Sorted Array

problem Suppose an array sorted in ascending order is rotated at some pivot unknown to you befo...

33. Search in Rotated Sorted Array

//本来想找到队列最小值,再进行二分查找,后来发现直接做也可以,但是if条件比较复杂 class Solution { public: int search(vector& nums, int...

LeetCode OJ 33 Search in Rotated Sorted Array

难度:hard 由此可见leetcode的hard难度比较于acm是偏简单一些的。 Suppose a sorted array is rotated at some pivot unkn...

leetcode 33. Search in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 mig...

leetcode解题之33&81. Search in Rotated Sorted Array java版(在旋转的数字中查找指定值)

33. Search in Rotated Sorted Array ,81. Search in Rotated Sorted Array II 。 leetcode解题之33&81. Search...

[leetcode] 33. Search in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 mig...

leetcode 33. Search in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 mig...

leetcode 33. Search in Rotated Sorted Array

题目大意:一个排序数组绕某个数选择了,在这个旋转后的数组中找指定的元素target 找到就返回在数组中的序号,否则返回-1 解题思路: 1、当然是可以直接搜的(复杂度O(n)),也可以过.但是对于有一...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)