forked from yuyongwei/Algorithms-In-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
largestNumberAtLeastTwiceOfOthers.swift
103 lines (83 loc) · 2.06 KB
/
largestNumberAtLeastTwiceOfOthers.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//
// largestNumberAtLeastTwiceOfOthers.swift
//
//
// Created by Dong, Anyuan (133) on 2019/4/5.
//
import Foundation
/*
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.
*/
//https://leetcode.com/problems/largest-number-at-least-twice-of-others/description/
/*
class Solution {
func dominantIndex(_ nums: [Int]) -> Int {
guard nums.count > 1 else {
return nums.count == 1 ? 0 : -1
}
let sort = nums.sorted()
let max = sort.last!
let sec = sort[nums.count - 2]
return max >= sec * 2 ? nums.index(of: max)! : -1
}
}
*/
/*
class Solution {
func dominantIndex(_ nums: [Int]) -> Int {
guard nums.count > 1 else {
return nums.count == 1 ? 0 : -1
}
var maxIndex = 0
var max = nums[maxIndex]
for i in 0..<nums.count {
if nums[i] > max {
max = nums[i]
maxIndex = i
}
}
for i in 0..<nums.count {
if i == maxIndex {
continue
}
if nums[i] * 2 > max {
return -1
}
}
return maxIndex
}
}
*/
class Solution {
func dominantIndex(_ nums: [Int]) -> Int {
guard nums.count > 1 else {
return nums.count == 1 ? 0 : -1
}
var maxIndex = 0
var max = 0
var sec = 0
if nums[0] > nums[1] {
max = nums[0]
sec = nums[1]
} else {
max = nums[1]
maxIndex = 1
sec = nums[0]
}
// print("before max:\(max), index:\(maxIndex), sec:\(sec)")
for (index, value) in nums.enumerated() {
if value > max {
sec = max
max = value
maxIndex = index
}
if value < max && value > sec {
sec = value
}
}
// print("after max:\(max), index:\(maxIndex), sec:\(sec)")
return max >= sec * 2 ? maxIndex : -1
}
}