Scribbling

[C++] vector<vector<int>> sorting with comparator 본문

Computer Science/C++

[C++] vector<vector<int>> sorting with comparator

focalpoint 2023. 9. 7. 02:32

LeetCode: 452. Minimum Number of Arrows to Burst Balloons

https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/description/?envType=study-plan-v2&envId=top-interview-150 

 

Minimum Number of Arrows to Burst Balloons - LeetCode

Can you solve this real interview question? Minimum Number of Arrows to Burst Balloons - There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xst

leetcode.com

 

class Solution {
public:
    int findMinArrowShots(vector<vector<int>>& points) {
		// using lambda comparator function
        sort(points.begin(), points.end(), [](const vector<int>& vec1, const vector<int>& vec2){
			return vec1[1] < vec2[1];
		});
		int ret = 1;
		int shot = points[0][1];
		for (int i=1; i<points.size(); i++) {
			if (points[i][0] <= shot) {
				continue;
			} else {
				shot = points[i][1];
				ret++;
			}
		}
		return ret;
    }
};

 

class Solution {
public:

    static bool cmp(vector<int>& a, vector<int>& b) { return a[1] < b[1]; }

    int findMinArrowShots(vector<vector<int>>& points) {
        sort(points.begin(), points.end(), cmp);
        int ret = 1;
        int end = points[0][1];
        for (int i = 1; i < points.size(); i++) {
            if (points[i][0] <= end) {
                continue;
            }
            ret++;
            end = points[i][1];
        }
        return ret;
    }
};