1.LeetCode:912. 排序数组
给你一个整数数组 nums,请你将该数组升序排列。
示例 1:
输入:nums = [5,2,3,1]
输出:[1,2,3,5]
示例 2:
输入:nums = [5,1,1,2,0,0]
输出:[0,0,1,1,2,5]
提示:
1 <= nums.length <= 5 * 1e4
-5 * 104 <= nums[i] <= 5 * 1e4
没什么好说的,直接调用api即可。
int cmp(int *a,int *b){
return *a-*b;
}
int* sortArray(int* nums, int numsSize, int* returnSize){
*returnSize=numsSize;
int *ans=(int*)malloc(sizeof(int)*(*returnSize));
for(int i=0;i<numsSize;i++){
ans[i]=nums[i];
}
qsort(ans,numsSize,sizeof(int),cmp);
return ans;
}
2.LeetCode:88. 合并两个有序数组
给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n ,分别表示 nums1 和 nums2 中的元素数目。
请你 合并 nums2 到 nums1 中,使合并后的数组同样按 非递减顺序 排列。
注意:最终,合并后数组不应由函数返回,而是存储在数组 nums1 中。为了应对这种情况,nums1 的初始长度为 m + n,其中前 m 个元素表示应合并的元素,后 n 个元素为 0 ,应忽略。nums2 的长度为 n 。
示例 1:
输入:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
输出:[1,2,2,3,5,6]
示例 2:
输入:nums1 = [1], m = 1, nums2 = [], n = 0
输出:[1]
示例 3:
输入:nums1 = [0], m = 0, nums2 = [1], n = 1
输出:[1]
提示:
nums1.length == m + n
nums2.length == n
0 <= m, n <= 200
1 <= m + n <= 200
-109 <= nums1[i], nums2[j] <= 109
类似于归并排序,不过由于数组可能含有前导零我们从末尾开始排序。
void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n)
{
int i=m+n-1,j=m-1,k=n-1;
while(k>=0||j>=0)
{
if(j==-1)
{
nums1[i]=nums2[k];
k--;
}
else if(k==-1)
{
break;
}
else if(nums1[j]>=nums2[k])
{
nums1[i]=nums1[j];
j--;
}
else
{
nums1[i]=nums2[k];
k--;
}
i--;
}
}
3.LeetCode:1037. 有效的回旋镖
给定一个数组 points ,其中 points[i] = [xi, yi] 表示 X-Y 平面上的一个点,如果这些点构成一个 回旋镖 则返回 true 。
回旋镖 定义为一组三个点,这些点 各不相同 且 不在一条直线上 。
示例 1:
输入:points = [[1,1],[2,3],[3,2]]
输出:true
示例 2:
输入:points = [[1,1],[2,2],[3,3]]
输出:false
提示:
points.length == 3
points[i].length == 2
0 <= xi, yi <= 100
这里就很简单了,我们学过高数了都知道判断两个向量共线的方法是看二者叉乘是否为0 ,a * b=|a| * |b| * sin<a,b>,如果结果为0则说明sin<a,b>为0,<a,b>为0或Π二者共线。所以将三个点变成两个向量判断叉乘是否为0即可
class Solution {
public:
bool isBoomerang(vector<vector<int>>& points) {
points[1][0]-=points[0][0];
points[1][1]-=points[0][1];
points[2][0]-=points[0][0];
points[2][1]-=points[0][1];
return points[1][0]*points[2][1]!=points[1][1]*points[2][0];
}
};
4.LeetCode:1232. 缀点成线
给定一个数组 coordinates ,其中 coordinates[i] = [x, y] , [x, y] 表示横坐标为 x、纵坐标为 y 的点。请你来判断,这些点是否在该坐标系中属于同一条直线上
示例 1:
输入:coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
输出:true
示例 2:
输入:coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
输出:false
提示:
2 <= coordinates.length <= 1000
coordinates[i].length == 2
-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
coordinates 中不含重复的点
和上题一样,挨个判断相邻两点是否共线,如果其中两个不共线直接返回false。
class Solution {
public:
bool checkStraightLine(vector<vector<int>>& coordinates) {
for(int i=1;i<coordinates.size();++i){
coordinates[i][0]-=coordinates[0][0];
coordinates[i][1]-=coordinates[0][1];
}
for(int i=2;i<coordinates.size();++i){
if(coordinates[i-1][0]*coordinates[i][1]!=coordinates[i-1][1]*coordinates[i][0]){
return false;
}
}
return true;
}
};