原题网址:https://leetcode.com/problems/convex-polygon/
Given a list of points that form a polygon when joined sequentially, find if this polygon is convex (Convex polygon definition).
Note:
- There are at least 3 and at most 10,000 points.
- Coordinates are in the range -10,000 to 10,000.
- You may assume the polygon formed by given points is always a simple polygon (Simple polygon definition). In other words, we ensure that exactly two edges intersect at each vertex, and that edges otherwise don't intersect each other.
Example 1:
[[0,0],[0,1],[1,1],[1,0]] Answer: True Explanation:
Example 2:
[[0,0],[0,10],[10,10],[10,0],[5,5]] Answer: False Explanation:思路:参考 https://discuss.leetcode.com/topic/70664/c-7-line-o-n-solution-to-check-convexity-with-cross-product-of-adajcent-vectors-detailed-explanation
Java代码:
public class Solution {
public boolean isConvex(List<List<Integer>> points) {
long prev = 0;
int n = points.size();
for(int i = 0; i < n; i++) {
int[][] m = new int[2][];
for(int j = 0; j < 2; j++) {
m[j] = new int[] {points.get((i+j+1)%n).get(0) - points.get(i).get(0),
points.get((i+j+1)%n).get(1) - points.get(i).get(1)};
}
long cur = det(m);
if (cur * prev < 0) return false;
prev = cur;
}
return true;
}
private long det(int[][] m) {
return m[0][0] * m[1][1] - m[0][1] * m[1][0];
}
}
C++代码:
class Solution {
public:
bool isConvex(vector<vector<int>>& points) {
long prev = 0;
int n = points.size();
for(int i = 0; i < n; i++) {
vector<vector<int>> m;
for(int j = 1; j < 3; j++) {
m.push_back({
points[(i+j)%n][0] - points[i][0],
points[(i+j)%n][1] - points[i][1]
});
}
long curr = det(m);
if (curr * prev < 0) return false;
prev = curr;
}
return true;
}
long det(vector<vector<int>>& m) {
return m[0][0] * m[1][1] - m[0][1] * m[1][0];
}
};
Python代码:
class Solution(object):
def det(self, m):
return m[0][0] * m[1][1] - m[0][1] * m[1][0]
def isConvex(self, points):
"""
:type points: List[List[int]]
:rtype: bool
"""
prev = 0
for i in range(len(points)):
m = []
for j in range(2):
m.append([
points[(i + j + 1) % len(points)][0] - points[i][0],
points[(i + j + 1) % len(points)][1] - points[i][1]])
curr = self.det(m)
if curr * prev < 0: return False
prev = curr
return True
JavaScript代码:
/**
* @param {number[][]} points
* @return {boolean}
*/
function det(m) {
return m[0][0] * m[1][1] - m[0][1] * m[1][0];
}
var isConvex = function(points) {
var prev = 0;
for(var i = 0; i < points.length; i++) {
var m = []
for(var j = 0; j < 2; j++) {
m.push([
points[(i+j+1)%points.length][0] - points[i][0],
points[(i+j+1)%points.length][1] - points[i][1]
]);
}
var curr = det(m);
if (curr * prev < 0) return false;
prev = curr;
}
return true;
};