Skip to content

469. Convex Polygon 👎

  • Time: $O(n)$
  • Space: $O(1)$
 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
class Solution {
 public:
  bool isConvex(vector<vector<int>>& points) {
    const int n = points.size();
    long sign = 0;

    for (int i = 0; i < points.size(); ++i) {
      const int cross =
          getCross(points[i], points[(i + 1) % n], points[(i + 2) % n]);
      if (cross == 0)  // p, q, r are collinear.
        continue;
      if (sign == 0)  // Find the first cross that's not 0.
        sign = cross;
      else if (cross * sign < 0)
        return false;
    }

    return true;
  }

 private:
  // Returns pq x qr.
  int getCross(const vector<int>& p, const vector<int>& q,
               const vector<int>& r) {
    return (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public boolean isConvex(List<List<Integer>> points) {
    final int n = points.size();
    long sign = 0;

    for (int i = 0; i < n; ++i) {
      final int cross = getCross(points.get(i), points.get((i + 1) % n), points.get((i + 2) % n));
      if (cross == 0) // p, q, r are collinear.
        continue;
      if (sign == 0) // Find the first cross that's not 0.
        sign = cross;
      else if (cross * sign < 0)
        return false;
    }

    return true;
  }

  // Returns pq x qr.
  private int getCross(List<Integer> p, List<Integer> q, List<Integer> r) {
    return (q.get(0) - p.get(0)) * (r.get(1) - p.get(1)) -
        (q.get(1) - p.get(1)) * (r.get(0) - p.get(0));
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def isConvex(self, points: list[list[int]]) -> bool:
    def getCross(p: list[int], q: list[int], r: list[int]):
      """Returns pq x qr."""
      return (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0])

    sign = 0
    for i in range(len(points)):
      cross = getCross(points[i - 2], points[i - 1], points[i])
      if cross == 0:  # p, q, r are collinear.
        continue
      if sign == 0:  # Find the first cross that's not 0.
        sign = cross
      elif cross * sign < 0:
        return False

    return True