forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Math] Add a solution to Line Reflection
- Loading branch information
Showing
2 changed files
with
35 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
/** | ||
* Question Link: https://leetcode.com/problems/line-reflection/ | ||
* Primary idea: Find a Line that should be y = (minX + maxX) / 2, then iterate through points and make sure that it has a reflected point in the opposite side. | ||
* | ||
* Time Complexity: O(n), Space Complexity: O(n) | ||
*/ | ||
|
||
class LineReflection { | ||
func isReflected(_ points: [[Int]]) -> Bool { | ||
var minX = Int.max, maxX = Int.min | ||
var pointSet = Set<[Int]>() | ||
|
||
for point in points { | ||
pointSet.insert(point) | ||
minX = min(point[0], minX) | ||
maxX = max(point[0], maxX) | ||
} | ||
|
||
let sum = minX + maxX | ||
|
||
for item in pointSet { | ||
if item[0] == sum { | ||
continue | ||
} | ||
|
||
if !pointSet.contains([sum - item[0], item[1]]) { | ||
return false | ||
} | ||
} | ||
|
||
return true | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters