Created
September 17, 2018 20:44
-
-
Save aligator4sah/7b984d25d7551944b2e51f845c6e6803 to your computer and use it in GitHub Desktop.
Leetcode 456 - 132 Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
public class NumberPattern { | |
//Solution 1: Naive solution | |
public boolean find132patternI(int[] nums) { | |
for (int i = 0; i < nums.length; i++) { | |
for (int j = i + 1; j < nums.length; j++) { | |
for (int k = j + 1; k < nums.length; k++) { | |
if (nums[i] < nums[k] && nums[k] < nums[j]) { | |
return true; | |
} | |
} | |
} | |
} | |
return false; | |
} | |
//Solution 2: | |
public boolean find132patternII(int[] nums) { | |
for (int j = 0, min = Integer.MAX_VALUE; j < nums.length; j++) { | |
min = Math.min(nums[j], min); | |
if (min == nums[j]) { | |
continue; | |
} | |
for (int k = nums.length - 1; k > j; k--) { | |
if (min < nums[k] && nums[k] < nums[j]) { | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
//Solution 3 | |
public boolean find132patternIII(int[] nums) { | |
int[] arr = Arrays.copyOf(nums, nums.length); | |
for (int i = 1; i < nums.length; i++) { | |
arr[i] = Math.min(nums[i - 1], arr[i - 1]); | |
} | |
for (int j = nums.length - 1, top = nums.length; j >= 0; j--) { | |
if (nums[j] < arr[j]) { | |
continue; | |
} | |
while (top < nums.length && arr[top] <= arr[j]) { | |
top++; | |
} | |
if (top < nums.length && nums[j] > arr[top]) { | |
return true; | |
} | |
arr[--top] = nums[j]; | |
} | |
return false; | |
} | |
//Solution 4 | |
public boolean find132patternIV(int[] nums) { | |
int n = nums.length; | |
int top = n; | |
int third = Integer.MIN_VALUE; | |
for (int i = n - 1; i >= 0; i--) { | |
if (nums[i] < third) { | |
return true; | |
} | |
while (top < n && nums[i] > nums[top]) { | |
third = nums[top++]; | |
} | |
nums[--top] = nums[i]; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment