leetcode 747. Largest Number Greater Than Twice of Others 最大元素的Index

素颜马尾好姑娘i 2022-06-03 08:56 206阅读 0赞

In a given integer array nums, there is always exactly one largest element.

Find whether the largest element in the array is at least twice as much as every other number in the array.

If it is, return the index of the largest element, otherwise return -1.

Example 1:
Input: nums = [3, 6, 1, 0]
Output: 1
Explanation: 6 is the largest integer, and for every other number in the array x,
6 is more than twice as big as x. The index of value 6 is 1, so we return 1.
Example 2:
Input: nums = [1, 2, 3, 4]
Output: -1
Explanation: 4 isn’t at least as big as twice the value of 3, so we return -1.
Note:
nums will have a length in the range [1, 50].
Every nums[i] will be an integer in the range [0, 99].

本题题意很简单,直接暴力去做即可

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <set>
  5. #include <queue>
  6. #include <stack>
  7. #include <string>
  8. #include <climits>
  9. #include <algorithm>
  10. #include <sstream>
  11. #include <functional>
  12. #include <bitset>
  13. #include <numeric>
  14. #include <cmath>
  15. #include <regex>
  16. using namespace std;
  17. class Solution
  18. {
  19. public:
  20. int dominantIndex(vector<int>& nums)
  21. {
  22. int largest = nums[0];
  23. int index = 0;
  24. for (int i = 0; i < nums.size(); i++)
  25. {
  26. if (nums[i] > largest)
  27. {
  28. largest = nums[i];
  29. index = i;
  30. }
  31. }
  32. for (int i = 0; i < nums.size(); i++)
  33. {
  34. if (i != index && largest < 2 * nums[i])
  35. return -1;
  36. }
  37. return index;
  38. }
  39. };

发表评论

表情:
评论列表 (有 0 条评论,206人围观)

还没有评论,来说两句吧...

相关阅读

    相关 0179-Largest Number( 数)

    > 这个系列算是出于个人兴趣开的一个新坑吧,最近看到同学刷LeetCode算法题,就想写写那些可以一行Python代码写出来的题目,因此本专栏的文章的解题方式效率不做保证,只为