日期:2014-05-20 浏览次数:20707 次
public static boolean isLegal(List<Integer> list) { boolean ret = true; int last = -Integer.MAX_VALUE; if (list.get(list.size() - 1) <= list.size()) { for (int i = 0; i < list.size(); i++) { if (list.get(i) < last) { ret = false; break; } last = list.get(i); } } else { ret = false; } return ret; }
------解决方案--------------------
public boolean validata(List<Integer> list){ Integer last = Integer.MAX_VALUE; int size = list.size(); //如果最后一个不等于list的长度则直接返回false if(size != list.get(size)){ return false; } for(int i = size - 1; i >= 0; i--){ int value = list.get(i); //如果后面一个比前面一个小,则直接返回false if(last < value){ return false; } last = value; } return true; }
------解决方案--------------------
public class ArraySetDemo { public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); System.out.println(check(list)); //true list.remove(2); //1 3 4 5 System.out.println(check(list)); //false list.add(1); //1 1 3 4 5 System.out.println(check(list)); //false } private static boolean check(List<Integer> list) { if (Collections.min(list)!=1) return false; if (Collections.max(list)!=list.size()) return false; Set<Integer> set = new HashSet<Integer>(); for(Integer i: list) set.add(i); if (set.size()<list.size()) return false; return true; } }
------解决方案--------------------
代码很干净,很简洁,还有一些细节可以改进,比如 ret的初始值设为false(这也是通常做法),这样后面可以省略几次赋值语句。-Integer.MAX_VALUE??