[Leetcode学习-java]Single Element in a Sorted Array(找出单一元素)

问题:

难度:easy

说明:

给一个sorted排序过的数组,然后找出其中只出现一次的元素,其他元素都出现两次。

要求:

时间复杂度O(log n),空间复杂度O(1)。

输入案例:

Example 1:

Input: [1,1,2,3,3,4,4,8,8]
Output: 2
Example 2:

Input: [3,3,7,7,10,11,11]
Output: 10

我的代码:

很简单的题目,主要是注意几个情况就是,具体写在代码测试数据中。

public class SingleElementinaSortedArray {
    public static void main(String[] args) {
        Solution solution = new SingleElementinaSortedArray().new Solution();

        // 其他元素出现 偶数次,Single在中中间的左边
        int[] arr = new int[]{1,1,2,3,3,4,4,8,8}; // 2
        // 其他元素出现 偶数次,Single在中间的右边
        int[] arr2 = new int[]{1,1,3,3,4,4,5,8,8}; // 5

        // 其他元素出现 奇数次,Single在中间的右边
        int[] arr3 = new int[]{3,3,7,7,10,11,11}; // 10
        // 其他元素出现 奇数次,Single在中间的左边
        int[] arr4 = new int[]{3,3,4,7,7,11,11}; // 4

        // 其他元素出现 奇数次,Single 末尾
        int[] arr5 = new int[]{1,1,2}; // 2
        // 其他元素出现 偶数次,Single 末尾
        int[] arr6 = new int[]{1,1,2,2,3}; // 3

        // 其他元素出现 奇数次,Single 开头
        int[] arr7 = new int[]{1,2,2}; // 1
        // 其他元素出现 偶数次,Single 开头
        int[] arr8 = new int[]{1,2,2,3,3}; // 1

        System.out.println(solution.singleNonDuplicate(arr));
        System.out.println(solution.singleNonDuplicate(arr2));
        System.out.println(solution.singleNonDuplicate(arr3));
        System.out.println(solution.singleNonDuplicate(arr4));
        System.out.println(solution.singleNonDuplicate(arr5));
        System.out.println(solution.singleNonDuplicate(arr6));
        System.out.println(solution.singleNonDuplicate(arr7));
        System.out.println(solution.singleNonDuplicate(arr8));
    }

    class Solution {
        public int singleNonDuplicate(int[] nums) {
            // 排除 长度1 和 开头
            if(nums.length < 2 || nums[0] != nums[1]) return nums[0];

            // 进行二分法处理
            int left = 0;
            int right = nums.length - 1;
            while(right > left) {
                int mid = left + right >> 1;
                boolean odd = mid % 2 != 0;
                if(nums[mid + 1] == nums[mid]) {
                    if(odd) right = mid - 1;
                    else left = mid + 1;
                } else if(nums[mid - 1] == nums[mid]) {
                    if(odd) left = mid + 1;
                    else right = mid - 1;
                } else return nums[mid];
            }
            return nums[left];
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值