中级农民
- 积分
- 155
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-4-17
- 最后登录
- 1970-1-1
|
写了下第一轮第一题
- public class DuplicateNumber {
- public static void main(String[] args) {
- int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
- System.out.println(findDuplicateNumber(arr));
- }
-
- public static int findDuplicateNumber(int[] arr) {
- if (arr == null || arr.length == 0) {
- return Integer.MAX_VALUE;
- }
- int start = 0;
- int end = arr.length - 1;
- while (start + 1 < end) {
- int mid = (end - start) / 2 + start;
- if (arr[mid] != mid + 1) {
- end = mid;
- } else {
- start = mid;
- }
- }
- if (arr[start] != start + 1) {
- return arr[start];
- } else if (arr[end] != end + 1) {
- return arr[end];
- }
- return Integer.MAX_VALUE;
- }
- }
复制代码 |
|