七月集训day03(排序)

912. 排序数组

在这里插入图片描述

代码/思路

class Solution {
public:
    vector<int> sortArray(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        return nums;
    }
};

/*
1- 很多语言都内置排序函数,复杂度为O(nlogn), 直接调用即可
2- 这题可以用来训练各种排序算法
*/

88. 合并两个有序数组

代码/思路

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        /*
        因为 nums1 的初始长度为 m + n,其中前 m 个元素表示应合并的元素,后 n 个元素为 0 ,应忽略。nums2 的长度为 n
        所以 可以直接把nums2的元素从num1的第m个元素开始,依次放入num1中
        */
        for(int i = 0; i < n; i++)
        {
           nums1[m + i] = nums2[i];
        }
        //最后返回排序的元素就可以
        sort(nums1.begin(), nums1.end());
    }
};

1037. 有效的回旋镖

代码/思路

class Solution {
public:
    bool isBoomerang(vector<vector<int>>& points) {
        //如果 x 坐标相同,则按 y 坐标排序; 否则按照 x 坐标排序
        sort(points.begin(), points.end(),
        [&](const vector<int>& a, const vector<int>& b){
            if(a[0] == b[0])
            {
                return a[1] < b[1];
            }
            return a[0] < b[0];
        });
        /*
        「三点各不相同且不在一条直线上」等价于「这两个向量的叉乘结果不为零」:
        */
        points[1][0] -= points[0][0];
        points[1][1] -= points[0][1];

        points[2][0] -= points[0][0];
        points[2][1] -= points[0][1];

        int cx = points[1][0] * points[2][1] -  points[1][1] * points[2][0];
        return cx != 0;
    }
};

912. 排序数组

代码/思路

class Solution {
public:
    bool checkStraightLine(vector<vector<int>>& coordinates) {
        sort(coordinates.begin(), coordinates.end(), 
        [&](const vector<int> &a, const vector<int> &b){
            if(a[0] == b[0])
            {
                return a[1] < b[1];
            }
            return a[0] < b[0];
        });

        //计算每个点的向量
        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][0] * coordinates[i - 1][1] != coordinates[i][1] * coordinates[i - 1][0])
            {
                return false;
            }
        }
        return true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值