LeetCode problem#162
Find Peak Element
Solved in 2 languagesRustJava
Solution
19 lines
1impl Solution {
2 pub fn find_peak_element(nums: Vec<i32>) -> i32 {
3 let mut left = 0;
4 let mut right = nums.len() - 1;
5
6 while left < right {
7 let mid = left + ((right - left) >> 1);
8
9 if nums[mid] > nums[mid + 1] {
10 right = mid;
11 }
12 else {
13 left = mid + 1;
14 }
15 }
16
17 return left as i32;
18 }
19}1class Solution {
2 public int findPeakElement(int[] nums) {
3 int left = 0;
4 int right = nums.length - 1;
5
6 while (left < right) {
7 int mid = left + ((right - left) >> 1);
8
9 if (nums[mid] > nums[mid + 1]) {
10 right = mid;
11 }
12 else {
13 left = mid + 1;
14 }
15 }
16
17 return left;
18 }
19}Want a walkthrough of this Rust solution?
Get a step-by-step explanation of the idea behind the code.
Want a walkthrough of this Java solution?
Get a step-by-step explanation of the idea behind the code.
Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.