Given an unsorted array return whether an increasing subsequence of
length 3 exists or not in the array. More specifically, if there exists i , j , k such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 return true else return false . Your function should run in O(n) time complexity and O(1) space complexity.
Examples:
Given [1, 2, 3, 4, 5] , return true .
Given [5, 4, 3, 2, 1] , return false .
實現代碼
IncreasingTripletSubsequence.javajava
package array; import java.util.Arrays; import util.Print; public class IncreasingTripletSubsequence { /** * 描述 Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array. More specifically, if there exists i , j , k such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 return true else return false . Your function should run in O(n) time complexity and O(1) space complexity. Examples: Given [1, 2, 3, 4, 5] , return true . Given [5, 4, 3, 2, 1] , return false . * 分析 對一個無序數組,判讀遞增3數列是否存在 * 直接解法 掃描數組,遍歷三遍 * 複雜度 時間(n^3),空間 (1) * @param nums * @return */ public boolean Solution1(int[] nums){ int min=nums[0]; for(int i=0;i<nums.length;i++) for(int j=i+1; j<nums.length;j++){ if(nums[i] >= nums[j]) continue; for(int k=j+1;k<nums.length;k++){ if(nums[k]>nums[j]){ Print.Int(nums[i]); Print.Int(nums[j]); Print.Int(nums[k]); return true; } } } return false; } /** * 夾逼解法 對每個i用j,k夾逼出結果 * 複雜度 時間O(n^2),,空間(1) * @param nums * @return */ public boolean Solution2(int[] nums){ for(int i=0;i<nums.length;i++){ int j = i+1; int k = nums.length-1; while(j<k){ while(nums[i]>=nums[j] && j<k) j++; while(nums[j]>=nums[k] && j<k ) k--; if(j<k) { Print.Int(nums[i]); Print.Int(nums[j]); Print.Int(nums[k]); return true; } //else break; } } return false; } /** * 時間優化解法 * 分析 掃描一遍數組,用變量 x1 保存當前最小的值,變量 x2 保存當前第二小的值。若是右面能碰到一個數大於 x2 ,說明必然存在一個遞增的三元組。 * 複雜度 空間(1),時間(n) */ public boolean Solution3(int[] nums){ int x1=Integer.MAX_VALUE, x2=Integer.MAX_VALUE; for(int i=0;i<nums.length;i++){ if(nums[i]<x1) x1=nums[i]; else if (nums[i]<x2) x2=nums[i]; else return true; } return false; } }
測試代碼
IncreasingTripletSubsequenceTest.java數組
package array; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class IncreasingTripletSubsequenceTest { private IncreasingTripletSubsequence s; @Before public void setUp() { s = new IncreasingTripletSubsequence(); } @Test public void testSolution1() { int[] nums = {3,4,1,7,5,2}; boolean expect = true; boolean result = s.Solution1(nums); System.out.println(result); Assert.assertEquals(expect, result); } @Test public void testSolution2() { int[] nums ={9,1,6,8,7}; boolean expect = true; boolean result = s.Solution2(nums); System.out.println(result); Assert.assertEquals(expect, result); } @Test public void testSolution3() { int[] nums ={5,4,3,2,1}; boolean expect = false; boolean result = s.Solution3(nums); System.out.println(result); Assert.assertEquals(expect, result); } }
結果測試
3 4 7 true 1 6 7 true false