Topic:1346. Check If N and Its Double Exist
Question description
Given an array of integers arr, check if there are two different indexes i and j, satisfies:
i != j0 <= i, j < arr.lengtharr[i] == 2 * arr[j]
Example
Example 1:
1 | 输入:arr = [10,2,5,3] |
Example 2:
1 | 输入:arr = [3,1,7,11] |
Constraints
2 <= arr.length <= 500-10³ <= arr[i] <= 10³
Problem-solving ideas
This problem can be solved in many ways. Let's analyze the two main solutions: brute force solution and hash table solution.
1. Violent solution
The most intuitive solution is to use a two-level loop to traverse all possible number pairs.
1 | def checkIfExist(arr): |
Complexity analysis:
- Time complexity: O(n²), where n is the array length
- Space complexity: O(1), only constant extra space used
2. Hash table solution
Using a hash table can significantly optimize the time complexity. We only need to traverse the array once and use a hash table to record the numbers we have encountered.
1 | def checkIfExist(arr): |
Complexity analysis:
- Time complexity: O(n), only needs to traverse the array once
- Space complexity: O(n), additional hash table space required
Code optimization case
Let's look at an initial version of the code and how to optimize it:
Original version:
1 | class Solution: |
Optimized version:
1 | class Solution: |
Optimization points
Data structure selection
- Use sets instead of dicts
- No need to store index information, only focus on the existence of values
code simplification
- Merge duplicate checking logic
- Remove unnecessary variables and calculations
- Use more concise conditional judgment
Performance improvements
- avoid using
hashmap.values()Traverse - O(1) finding properties using sets
- Reduce double counting
- avoid using
Key points to note
Boundary case handling
- Consider the case where there are 0 in the array (twice 0 is still 0)
- Pay attention to the handling of negative numbers
- Make sure not to use the same index (i != j)
Numerical check
- Need to check twice and half of a number at the same time
- Make sure the number is even when checking half
Performance optimization
- Use appropriate data structures (collections)
- Avoid unnecessary calculations and traversals
Summary
This question shows how to improve algorithm performance by selecting appropriate data structures and optimizing code logic. From the initial brute force solution to the use of hash tables to the optimization of the code, each step has brought significant improvements. The final solution not only runs efficiently, but the code is concise and easy to understand.
The key is to understand:
- Although the brute force solution is intuitive, it is inefficient
- Hash tables provide optimal time and space trade-offs
- Code optimization is not only for efficiency, but also for readability and maintainability