Leetcode C++ 《第175场周赛-1 》5332.检查整数及其两倍数是否存在

Leetcode C++ 《第175场周赛-1 》5332.检查整数及其两倍数是否存在

  1. 题目
    给你一个整数数组 arr,请你检查是否存在两个整数 N 和 M,满足 N 是 M 的两倍(即,N = 2 * M)。

更正式地,检查是否存在两个下标 i 和 j 满足:

i != j
0 <= i, j < arr.length
arr[i] == 2 * arr[j]

示例 1:

输入:arr = [10,2,5,3]
输出:true
解释:N = 10 是 M = 5 的两倍,即 10 = 2 * 5 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/check-if-n-and-its-double-exist
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  1. 思路
  • 先排序,排序之后遍历数组,逐个找每个元素的2倍
    • 如果是负数x,在左边二分法找2x
    • 如果是正数x,在右边二分法找2x
  • 时间复杂度:nlogn
  1. 代码
class Solution {
public:
    bool checkIfExist(vector<int>& arr) {
        sort(arr.begin(), arr.end());
        for (int i = 0; i < arr.size(); i++) {
            int one = arr[i];
            int key = one * 2;
            if (one >= 0) {
                if (getKIndex(arr, i+1, arr.size()-1, key) != -1)
                    return true;
            
            } else {
                if (getKIndex(arr, 0, i-1, key) != -1)
                    return true;
            }
        }
        return false;
    }
    
    int getKIndex(vector<int> nums, int startIndex, int endIndex, int k) {
        int mid;
        while (startIndex <= endIndex) {
            mid = (startIndex + endIndex) >> 1;
            if (nums[mid] == k)
                return mid;
            else if (nums[mid] < k) {
                startIndex = mid + 1;
            } else {
                endIndex = mid -1;
            }
        }
        return -1;
    }
};
发布了205 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Alexia23/article/details/104238962