赞
踩
LeetCode162.寻找峰值
难度:中等
目录
- class Solution {
- public int findPeakElement(int[] nums) {
- if (nums.length == 1) {
- return 0;
- }else if (nums.length == 2) {
- return nums[0] > nums[1] ? 0 : 1;
- }
- var max = Integer.MIN_VALUE;
- var maxIndex = 0;
- for (int i = 0; i < nums.length; i++) {
- if (nums[i] > max) {
- max = nums[i];
- maxIndex = i;
- }
- }
- return maxIndex;
- }
- // 改进版
- public int findPeakElement(int[] nums) {
- var maxIndex = -1;
- var max = Integer.MIN_VALUE;
- for (int i = 0; i < nums.length; i++) {
- if (nums[i] > max) {
- max = nums[i];
- maxIndex = i;
- }
- }
- return maxIndex
- }
- }
- class Solution {
- public int findPeakElement(int[] nums) {
- int step = (int) (Math.random() * nums.length);
- while (!(compare(nums,step-1,step) < 0 && compare(nums,step,step+1) > 0)) {
- if (compare(nums,step,step+1) < 0) {
- step++;
- }else {
- step--;
- }
- }
- return step;
- }
-
-
- public int[] get(int[] nums,int index) {
- if (index == nums.length || index == -1) {
- return new int[] {0,0};
- }
- return new int[] {1,nums[index]};
- }
-
- public int compare (int[] nums,int index1,int index2) {
- var num1 = get(nums,index1);
- var num2 = get(nums,index2);
- if (num1[0] != num2[0]) {
- return num1[0] - num2[0];
- }else {
- return num1[1] - num2[1];
- }
- }
-
- }
- class Solution {
- public int findPeakElement(int[] nums) {
- var left = 0;
- var right = nums.length - 1;
- var top = -1;
- while (left <= right) {
- var mid = (left + right) / 2;
- if (compare(nums,mid,mid+1) > 0 && compare(nums,mid,mid-1) > 0) {
- top = mid;
- break;
- }
- if (compare(nums,mid,mid+1) < 0) {
- left = mid + 1;
- }else {
- right = mid - 1;
- }
- }
- return top;
- }
- public int[] get(int[] nums,int index) {
- if (index == nums.length || index == -1) {
- return new int[] {0,0};
- }
- return new int[] {1,nums[index]};
- }
-
- public int compare (int[] nums,int index1,int index2) {
- var num1 = get(nums,index1);
- var num2 = get(nums,index2);
- if (num1[0] != num2[0]) {
- return num1[0] - num2[0];
- }else {
- return num1[1] - num2[1];
- }
- }
- }
该算法有爬坡和取最大值,更形象的是爬坡算法,但是代码量稍微有点大,取最大值虽有一些抽象,但是比较简单,两个算法都可以,但是比较推荐取最大值,该算法时间消耗的较少
最后总结必须要掌握的几点
1.爬坡算法的思想与进阶思想
2.取最大值的思想
3.代码实现
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。