-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path0469-convex-polygon.js
More file actions
44 lines (40 loc) · 1.17 KB
/
0469-convex-polygon.js
File metadata and controls
44 lines (40 loc) · 1.17 KB
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
/**
* 469. Convex Polygon
* https://leetcode.com/problems/convex-polygon/
* Difficulty: Medium
*
* You are given an array of points on the X-Y plane points where points[i] = [xi, yi].
* The points form a polygon when joined sequentially.
*
* Return true if this polygon is convex and false otherwise.
*
* You may assume the polygon formed by given points is always a simple polygon. In other
* words, we ensure that exactly two edges intersect at each vertex and that edges otherwise
* don't intersect each other.
*/
/**
* @param {number[][]} points
* @return {boolean}
*/
var isConvex = function(points) {
const n = points.length;
let prevSign = 0;
for (let i = 0; i < n; i++) {
const p1 = points[i];
const p2 = points[(i + 1) % n];
const p3 = points[(i + 2) % n];
const dx1 = p2[0] - p1[0];
const dy1 = p2[1] - p1[1];
const dx2 = p3[0] - p2[0];
const dy2 = p3[1] - p2[1];
const crossProduct = dx1 * dy2 - dy1 * dx2;
const currentSign = Math.sign(crossProduct);
if (currentSign !== 0) {
if (prevSign !== 0 && currentSign !== prevSign) {
return false;
}
prevSign = currentSign;
}
}
return true;
};