int length = 20; int[] data = newint[length]; Random random = new Random(); for (int i = 0; i < length; i++) { data[i] = random.nextInt(2); } getMaxSuccessiveLength1(data); getMaxSuccessiveLength2(data); }
privatestaticintgetMaxSuccessiveLength2(int[] numbers){ int result = 0; int successiveLength = 0; //连续1的个数 int accessTime = 0; //从数组读取的次数 for (int i = 0; i < numbers.length; ) { accessTime++; if (numbers[i] == 0) { result = (result > successiveLength) ? result : successiveLength; successiveLength = 0; i += 1; } else { successiveLength++; if (shouldJump(successiveLength)) { result = (result > successiveLength) ? result : successiveLength; int jumpDistance = result; if (i + jumpDistance > numbers.length - 1) { jumpDistance = numbers.length - 1 - i; } if (jumpDistance == 0) { break; } i += jumpDistance; for (int j = i; j > i - jumpDistance; j--) { if (numbers[j] == 0) { i = j + 1; successiveLength = 0; accessTime++; break; } else { accessTime++; if (j == i - result + 1) { successiveLength += jumpDistance; // 这一段是连续的1 result = (result > successiveLength) ? result : successiveLength; i++; } } } } else { i++; result = (result > successiveLength) ? result : successiveLength; } } } System.out.println("getMaxSuccessiveLength2 = " + result + ",accessTime = " + accessTime); return result; }