-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0469-convex-polygon.js
More file actions
38 lines (30 loc) · 938 Bytes
/
0469-convex-polygon.js
File metadata and controls
38 lines (30 loc) · 938 Bytes
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
/**
* Convex Polygon
* Time Complexity: O(n)
* Space Complexity: O(1)
*/
var isConvex = function (points) {
const pointCount = points.length;
let lastValidSign = 0;
let loopIndex = 0;
while (loopIndex < pointCount) {
const vertexA = points[loopIndex];
const vertexB = points[(loopIndex + 1) % pointCount];
const vertexC = points[(loopIndex + 2) % pointCount];
const deltaXA = vertexB[0] - vertexA[0];
const deltaYA = vertexB[1] - vertexA[1];
const deltaXB = vertexC[0] - vertexB[0];
const deltaYB = vertexC[1] - vertexB[1];
const computedCrossProduct = deltaXA * deltaYB - deltaYA * deltaXB;
const computedTurnSign = Math.sign(computedCrossProduct);
if (computedTurnSign === 0) {
} else {
if (lastValidSign !== 0 && computedTurnSign !== lastValidSign) {
return false;
}
lastValidSign = computedTurnSign;
}
loopIndex++;
}
return true;
};