Leetcode 3151. Special Array I
You are given a non-negative integer array numList
. A special integer num
is defined as the number of i
(where 0 <= i < numList.length
) such that numList[i] % num == 0
and numList[i] / num
is not an integer. You are to return num
.
numList
have repeated numbers?
num
that satisfies the conditions described?
num
exists, we can return -1
.We need to find a special integer num
such that:
i
in the range [0, numList.length)
, numList[i] % num == 0
.i
, numList[i] / num
is not an integer.Steps:
num
from 1
to the largest number present in numList
.-1
.#include <iostream>
#include <vector>
#include <algorithm>
int findSpecialInteger(const std::vector<int>& numList) {
int maxElement = *std::max_element(numList.begin(), numList.end());
for (int num = 1; num <= maxElement; ++num) {
bool isSpecial = true;
for (int i = 0; i < numList.size(); ++i) {
if (numList[i] % num != 0 || numList[i] / num == 0 || numList[i] / num == 1) {
isSpecial = false;
break;
}
}
if (isSpecial) {
return num;
}
}
return -1;
}
int main() {
std::vector<int> numList = {8, 12, 10, 20};
int result = findSpecialInteger(numList);
std::cout << "Special integer: " << result << std::endl;
return 0;
}
numList
.num
:
1
to the maximum element which is (O(\max(numList))).numList
, which is (O(n)).Therefore, the overall time complexity is (O(n \times \max(numList))).
This solution may not be the most efficient for very large values of numList
, but it should work within reasonable constraints of typical interview problems. For more optimizations, additional mathematical insights or constraints need to be evaluated.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?