2025年6月19日 星期四

1346. Check If N and Its Double Exist

1346. Check If N and Its Double Exist

難度: Easy
類型: Array, Hash Table, Two Pointers, Binary Search, Sorting
C程式下載: 1346.c

前情題要:
檢查陣列中是否有兩個數, 一個數是另一個數的兩倍。

Given an array arr of integers, check if there exist two indices i and j such that :

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

 

Example 1:

Input: arr = [10,2,5,3]
Output: true
Explanation: For i = 0 and j = 2, arr[i] == 10 == 2 * 5 == 2 * arr[j]

Example 2:

Input: arr = [3,1,7,11]
Output: false
Explanation: There is no i and j that satisfy the conditions.

 

Constraints:

  • 2 <= arr.length <= 500
  • -103 <= arr[i] <= 103
思考方式:
1. 每個數跟它後面的每一個數字比較, 是否為該數字的兩倍或二分之一。

複雜度思考:

Time Complexity: O( 0.5*N^2 ) 

Space Complexity: O( x )

結果:

Runtime: 0 ms, Beats: 100%

Memory: 8.47 MB, Beats: 29.94%

Accepted
112 / 112 testcases passed
tendchen
tendchen
submitted at Apr 29, 2025 12:55
Runtime
0ms
Beats100.00%
Analyze Complexity
Memory
8.47MB
Beats29.94%
Analyze Complexity
2ms4ms6ms8ms0%25%50%75%100%
avatar
2ms4ms6ms8ms
Code
C
bool checkIfExist(int* arr, int arrSize) {
    int i,j;
    for (i=0;i<arrSize;i++)
    {
        for (j=i+1;j<arrSize;j++)
        {
            if ((arr[i]==arr[j]*2)||(arr[j]==arr[i]*2))
                return true;
        }
    }
    return false;
}