1346. Check If N and Its Double Exist
Difficulty: Easy
Topics: Array, Hash Table, Two Pointers, Binary Search, Sorting
Given an array arr of integers, check if there exist two indices i and j such that :
Example 1:
Example 2:
Constraints:
Hint:
Solution:
We can use a hash table (associative array) to track the elements we have already encountered while iterating through the array. The idea is to check for each element arr[i] if its double (i.e., 2 * arr[i]) or half (i.e., arr[i] / 2 if it's an even number) has already been encountered.
Here’s a step-by-step solution:
Let's implement this solution in PHP: 1346. Check If N and Its Double Exist
Explanation:
- Hash Table: We use the $hashTable associative array to store the elements we've encountered so far.
- First Condition: For each element arr[i], we check if arr[i] * 2 exists in the hash table.
- Second Condition: If the element is even, we check if arr[i] / 2 exists in the hash table.
- Adding to Hash Table: After checking, we add arr[i] to the hash table for future reference.
- Return: If we find a match, we immediately return true. If no match is found after the loop, we return false.
Time Complexity:
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Check If N and Its Double Exist. For more information, please follow other related articles on the PHP Chinese website!