Sponsored
Sponsored
This approach involves using a hash map or dictionary to count the number of occurrences of each integer in the array. After counting, we identify numbers that appeared only once and find the maximum among them. This way, we can efficiently determine the largest single number.
Time Complexity: O(n^2) in worst case for counting and sorting (since sorting involves iterating the elements list).
Space Complexity: O(n) for storing numbers and their counts.
1function biggestSingleNumber(nums) {
2 const numCount = {};
3 for (const num of nums) {
4 numCount[num] = (numCount[num] || 0) + 1;
5 }
6
7 let maxNum = -Infinity;
8 for (const [num, count] of Object.entries(numCount)) {
9 if (count === 1) {
10 maxNum = Math.max(maxNum, parseInt(num));
11 }
12 }
13
14 return maxNum === -Infinity ? null : maxNum;
15}
16
17const nums = [8, 8, 3, 3, 1, 4, 5, 6];
18const result = biggestSingleNumber(nums);
19console.log(result !== null ? result : "null");
This JavaScript solution leverages an object to map numbers to their counts. Afterwards, it checks for entries with a count of one to identify and print the largest single occurrence number.
This approach involves sorting the numbers first. After sorting, we can iterate through the list to count numbers that appear consecutively more than once and skip them. The largest number with only one occurrence is then the answer.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(1) as we sort in place.
1#include <vector>
#include <algorithm>
using namespace std;
int biggestSingleNumber(vector<int>& nums) {
if (nums.empty()) return -1;
sort(nums.begin(), nums.end(), greater<int>());
for (size_t i = 0; i < nums.size(); ++i) {
if ((i == 0 || nums[i] != nums[i - 1]) &&
(i == nums.size() - 1 || nums[i] != nums[i + 1])) {
return nums[i];
}
}
return -1;
}
int main() {
vector<int> nums = {8, 8, 3, 3, 1, 4, 5, 6};
int result = biggestSingleNumber(nums);
cout << (result == -1 ? "null" : to_string(result)) << endl;
return 0;
}
In C++, we sort the given array in descending order, allowing us to iterate over it and easily identify numbers that occur only once.