有这样一个数组,[-4, -3, -2, -1, 2, 3, 5, 6, 7, 9, 12, 33, 35],找出它的最长连续子数组,如这个数组的最长连续子数组是-4, -3, -2, -1。
我的思路:1、将数组元素放入二叉树 2、对二叉树使用中序排列,得到一个有序数组 3、对有序数组元素进行-1判断,获得最长连续数组。
具体代码:
1、Node类,二叉树元素
public class Node { public Object data; public Node left; public Node right; public int state=0; public Node(Object data){ this.data=data; }
}
2、BinarySearcheTree类,二叉树的新增元素、中序排序方法
public class BinarySearchTree<T extends Comparable<T>> {
public Node root;/** * 非递归中序遍历 * */ public List midOrderWithoutRecures(){ List array = new ArrayList(); if(root==null){ return null; } Stack<Node> stack = new Stack(64); stack.push(root); Node current; int i = 0; while (!stack.isEmpty()){ current=stack.getTop(); if(current.state==0){ if(current.left!=null){ stack.push(current.left); } current.state=1; } else if(current.state==1){ array.add(current.data); current.state=2; i++; } else if(current.state==2){ if(current.right!=null){ stack.push(current.right); } current.state=3; } else if(current.state==3){ stack.pop(); current.state=0; } } return array; }
}
3、main方法
public static void main(String[] args){ BinarySearchTree binarySearchTree = new BinarySearchTree(); int[] srcArray = new int[]{-4, -3, -2, -1, 2, 3, 5, 6, 7, 9, 12, 33, 35}; for(int i:srcArray){ binarySearchTree.insert(i); } List<Integer> orderedArray = binarySearchTree.midOrderWithoutRecures(); System.out.println("排序后数组:"+orderedArray); /*LinkedHashMap是有序不重复数组*/ Map childArray = new LinkedHashMap();//存放当前连续数组 Map longestChildArray = new LinkedHashMap();//存放当前最长连续数组 boolean serial = false;//标记变量,标记目前是否是连续的 for(int j=0;j<orderedArray.size()-1;j++){ if(orderedArray.get(j+1)-orderedArray.get(j)==1){ serial = true; childArray.put(orderedArray.get(j),1); childArray.put(orderedArray.get(j+1),1); }else { serial = false; } //serial是false,说明当前连续已被断开 if(!serial){ //通过比较本次连续子数组的长度和之前连续子数组的长度来看是否要替换 if(childArray.size()>longestChildArray.size()){ longestChildArray = childArray; } //清空childArray,放置新的连续数组 childArray = new LinkedHashMap();// } } System.out.println("最长数组:"+longestChildArray.keySet()); }
如果看到的大家有更好更高效的解决办法,欢迎讨论。