Interview-Increasing Sequence with Length 3.

时间:2023-03-09 02:31:49
Interview-Increasing Sequence with Length 3.

Given an array, determine whether there are three elements A[i],A[j],A[k], such that A[i]<A[j]<A[k] & i<j<k.

Analysis:

It is a special case of the Longest Increasing Sequence problem. We can use the O(nlog(n)) algorithm, since we only need sequence with length three, we can do it in O(n).

Solution:

 public static boolean threeIncSeq(int[] A){
if (A.length<3) return false; int oneLen = 0;
int twoLen = -1;
for (int i=1;i<A.length;i++){
//check whether current element is larger then A[twoLen].
if (twoLen!=-1 && A[i]>A[twoLen]) return true;
if (twoLen!=-1 && A[i]>A[twoLen] && A[i]<A[oneLen]){
twoLen = i;
continue;
}
if (twoLen==-1 && A[i]>A[oneLen]){
twoLen = i;
continue;
}
if (A[i]<A[oneLen]){
oneLen = i;
continue;
}
} return false;
}

Variant:

If we need to output the sequence, we then need to record the sequence of current length 1 seq and length 2 seq.

 public static List<Integer> threeIncSeq(int[] A){
if (A.length<3) return (new ArrayList<Integer>()); int oneLen = 0;
int twoLen = -1;
List<Integer> oneList = new ArrayList<Integer>();
List<Integer> twoList = new ArrayList<Integer>();
oneList.add(A[0]);
for (int i=1;i<A.length;i++){
//check whether current element is larger then A[twoLen].
if (twoLen!=-1 && A[i]>A[twoLen]){
twoList.add(A[i]);
return twoList;
}
if (twoLen!=-1 && A[i]>A[twoLen] && A[i]<A[oneLen]){
twoLen = i;
twoList = new ArrayList<Integer>();
twoList.addAll(oneList);
twoList.add(A[i]);
continue;
}
if (twoLen==-1 && A[i]>A[oneLen]){
twoLen = i;
twoList = new ArrayList<Integer>();
twoList.addAll(oneList);
twoList.add(A[i]);
continue;
}
if (A[i]<A[oneLen]){
oneLen = i;
oneList = new ArrayList<Integer>();
oneList.add(A[i]);
continue;
}
} return (new ArrayList<Integer>()); }

NOTE: This is more compliated then needed, when using List<> in this case, but this idea can be used to print the LIS.