find peak or drop
来源:互联网 发布:盐城金石计价软件 编辑:程序博客网 时间:2024/05/16 11:33
//http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=156077&extra=page%3D2%26filter%3Dsortid%26sortid%3D311%26searchoption%5B3046%5D%5Bvalue%5D%3D2%26searchoption%5B3046%5D%5Btype%5D%3Dradio%26sortid%3D311
找打peak or drop,原来用的是递归,这次改为迭代
public static int helper1(int[] nums) { if (nums.length == 0) return -1; int len = nums.length; if (Math.abs(nums[len - 1] - nums[0]) == len - 1) return -1;// There is no such a valley or peak int start = 0, end = nums.length - 1; while (start < end) { int mid = start + (end - start) / 2; if ((nums[mid - 1] - nums[mid]) * (nums[mid + 1] - nums[mid]) > 0) return nums[mid]; int diffOfIndex = mid - start; int diffOfValue = Math.abs(nums[mid] - nums[start]); //因为如果不相差,则下标和值是对应的,则没有发生波峰或波谷 if (diffOfIndex == diffOfValue) start = mid; else end = mid; } return -1;}public static void main(String[] args) {int[] nums1 = { 1, 2, 3, 4, 3, 2 };int[] nums2 = {};int[] nums3 = { 1, 2, 3, 4, 5, 6, 7, 8, 7 };int[] nums4 = { 1, 2, 3, 4, 5 };int[] nums5 = { 5, 4, 3, 2, 1, 2, 3 };int[] nums6 = { 9, 8, 7, 6, 7 };System.out.println(find(nums1));System.out.println(find(nums2));System.out.println(find(nums3));System.out.println(find(nums4));System.out.println(find(nums5));System.out.println(find(nums6));System.out.println(helper1(nums1)); System.out.println(helper1(nums2)); System.out.println(helper1(nums3)); System.out.println(helper1(nums4)); System.out.println(helper1(nums5)); System.out.println(helper1(nums6));}
0 0
- find peak or drop
- [LeetCode] Find Peak Element
- Find Peak Element
- Leetcode:Find Peak Element
- Find Peak Element
- Find Peak Element
- Find Peak Element
- LeetCode Find Peak Element
- leetcode: Find Peak Element
- leetcode:Find Peak Element
- Find Peak Element
- Find Peak Element
- Find Peak Element
- LeetCode Find Peak Element
- Find Peak Element --leetcode
- Leetcode Find Peak Element
- [LeetCode] Find Peak Element
- Find Peak Element [Medium]
- poj1050
- 树链剖分学习笔记
- ubuntu开机进入命令行界面与图形界面之间的切换
- 31岁大叔自学android的一点感悟
- Eclipse的working Set里面的东西存储在哪个文件中
- find peak or drop
- python导入自定义模块
- 一个关于SMTP 的封装类
- HttpClient对于https的支持和配置
- mysql入门
- 实现右下角提示框
- phpcms实现微信登陆(无需注册,直接存入)
- Handle机制详解
- C++ 引用和指针的区别 常量指针和指针常量的区别