标签:interview
Question:
Given an array, does it exist that
i < j < k where A[i] < A[J] < [K].
// Option 1. // Brute force. // Given any index i, return true if there exists: // A[m] < A[i], m < i // A[n] > A[i], n > i boolean hasLessInLeft(int[] a, int i) { for (int index = 0 ; index < i ; index ++) { if (a[index] < a[i]) return true; } return false; } boolean hasMoreInRight(int[] a, int i) { ... } // O(n ^ 2) boolean has3Increasing(int[] a) { for (int i = 0 ; i < a.length ; i ++) { if (hasLessInLeft(a, i) && hasMoreInRight(a, i)) return true; } return false; } // A better solution? // maintain min, mid boolean has3Increasing(int[] a) { Integer min = null; Integer mid = null; for (int i : a) { if (min == null || i < min) { min = i; } else if (mid == null || i < mid) { mid = i } else if (i > mid) // This means there must be a min before mid. { return true; } } return false; }
标签:interview
原文地址:http://7371901.blog.51cto.com/7361901/1589954