File tree Expand file tree Collapse file tree 1 file changed +84
-0
lines changed Expand file tree Collapse file tree 1 file changed +84
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ 在一个给定的数组nums中,总是存在一个最大元素 。
3
+
4
+ 查找数组中的最大元素是否至少是数组中每个其他数字的两倍。
5
+
6
+ 如果是,则返回最大元素的索引,否则返回-1。
7
+
8
+ 示例 1:
9
+
10
+ 输入: nums = [3, 6, 1, 0]
11
+ 输出: 1
12
+ 解释: 6是最大的整数, 对于数组中的其他整数,
13
+ 6大于数组中其他元素的两倍。6的索引是1, 所以我们返回1.
14
+
15
+
16
+
17
+ 示例 2:
18
+
19
+ 输入: nums = [1, 2, 3, 4]
20
+ 输出: -1
21
+ 解释: 4没有超过3的两倍大, 所以我们返回 -1.
22
+
23
+
24
+
25
+ 提示:
26
+
27
+ nums 的长度范围在[1, 50].
28
+ 每个 nums[i] 的整数范围在 [0, 99].
29
+ */
30
+
31
+ int dominantIndex(int* nums, int numsSize)
32
+ {
33
+ int max = -1;
34
+ int max_index;
35
+ for(int i = 0; i < numsSize; i++)
36
+ {
37
+ if(nums[i] > max)
38
+ {
39
+ max = nums[i];
40
+ max_index = i;
41
+ }
42
+ }
43
+ for(int j = 0; j < numsSize; j++)
44
+ {
45
+ if(nums[j] != max && max < nums[j] * 2)
46
+ return -1;
47
+ }
48
+ return max_index;
49
+ }
50
+
51
+ /*
52
+ 这种解法为两次循环解法,第一次循环找到数组中最大的数max及其下标max_index,
53
+ 第二次循环则判断max是否是其他数字的至少两倍大,如果发现不满足条件的,直接返回
54
+ -1,否则,返回记录的最大数字的下标max_index。
55
+ */
56
+
57
+ int dominantIndex(int* nums, int numsSize){
58
+ int dex=-1,first=-1,second;
59
+ for(int i=0;i<numsSize;i++)
60
+ {
61
+ if(nums[i]>first)
62
+ {
63
+ second=first;
64
+ first=nums[i];
65
+ dex=i;
66
+
67
+ }
68
+ if(nums[i]<first&&nums[i]>second)
69
+ {
70
+ second=nums[i];
71
+ }
72
+ }
73
+ if(first>=2*second)
74
+ return dex;
75
+ else
76
+ return -1;
77
+ }
78
+ /*
79
+ 这种解法为一次循环法,
80
+ 将待解决的问题转换为数组中第一大数字first和第二大数字second之间的关系比较,
81
+ 如果first至少是second的两倍大小,则它一定也是其余数字的至少两倍大小,
82
+ 所以一边循环找到数组中的第一大的数字first和第二大的数字second,并比较它俩
83
+ 之间的大小关系即可。
84
+ */
You can’t perform that action at this time.
0 commit comments