Leetcode进阶之路——Weekly Contest 142

https://leetcode.com/problems/statistics-from-a-large-sample/
Leetcode进阶之路——Weekly Contest 142_第1张图片
给定一个长为255的整型数组count, count[k]表示下标为k的数字出现了count[k]次
求所有数的最小值、最大值、均值、中位数以及众数
遍历的同时记录即可,对这几个概念理解基本就OK

class Solution {
public:
    vector sampleStats(vector& count) {
		long long int sum = 0, cnt = 0;
		for (int i = 0; i < count.size(); ++i)
			if(count[i])
				cnt += count[i], sum += (count[i] * i);
        
		int left = 0, right = 0;
		if (cnt % 2) left = cnt / 2 + 1, right = cnt / 2 + 1;
		else left = cnt / 2, right = cnt / 2 + 1;
        
		vector res;
		for (int i = 0; i < count.size(); ++i)
			if (count[i])
			{
				res.emplace_back(i);
				break;
			}
		for (int i = count.size() - 1; i >= 0; --i)
			if (count[i])
			{
				res.emplace_back(double(i));
				break;
			}
		res.emplace_back(sum * 1.0 / cnt);
        
		long long int maxcnt = 0, maxn = 0, curcnt = 0, pren = 0, flag = true;
		for (int i = 0; i < count.size(); ++i)
		{
			if (count[i] > maxcnt)
			{
				maxcnt = count[i];
				maxn = i;
			}
			if (flag && curcnt + count[i] >= right)
			{
				flag = false;
				if (left == right) left = i, right = i;
				else
				{
					if (curcnt == left)
					{
						left = pren, right = i;
					}
					else left = i, right = i;
				}
			}
			if (count[i])
			{
				pren = i;
				curcnt += count[i];
			}
		}
		res.emplace_back((left + right) / 2.0);
		res.emplace_back(maxn);
		return res;
	}
};

1094. Car Pooling
Leetcode进阶之路——Weekly Contest 142_第2张图片
给定一个二维整型数组,每个元素包含三个字段:[num_passengers, start_location, end_location], 即在start上车、end下车的乘客数。车辆只能一直往目的地开,不能往回开,求是否能带上所有乘客
用pair存储一个乘客的上车点和下车点,然后整个遍历一遍,若到了上车点则+乘客数,到了下车点则-乘客数,判断是否有超载的情况发生,若有则返回false,否则返回true

class Solution {
public:
    bool carPooling(vector>& trips, int capacity) {
        vector> vp;
        for(auto v: trips)
        {
            vp.emplace_back(make_pair(v[1], v[0]));
            vp.emplace_back(make_pair(v[2], -v[0]));
        }
		
        sort(vp.begin(), vp.end());
        for(auto p: vp)
        {
            capacity -= p.second;
            if(capacity < 0) return false;
        }
		return true;
	}
};


Leetcode进阶之路——Weekly Contest 142_第3张图片
给定一个整型mountain数组,即必定存在一个位置,使得在该元素前为递增,该元素后为递减
再给一个target,判断该数是否存在于数组中,若存在多处,返回较小的index
这里规定了只能用mountainArray.get(k)函数来获取第k个下标对应的值,且对该函数的调用次数不得超过100
因此需要三次二分,分别用于:

  • 找到分界点
  • 在分界点前找target(若找到,直接返回)
  • 在分界点后找target(若找到,直接返回)
    若未找到,则返回-1
/**
 * // This is the MountainArray's API interface.
 * // You should not implement it, or speculate about its implementation
 * class MountainArray {
 *   public:
 *     int get(int index);
 *     int length();
 * };
 */
class Solution {
public:
    int findInMountainArray(int target, MountainArray &mountainArr) {
		int left = 0, middle = mountainArr.length() - 1, right = mountainArr.length() - 1;
		while(left < middle)
        {
            int mid = (left + middle) / 2;
            if(mountainArr.get(mid) > mountainArr.get(mid + 1)) 
                middle = mid;
            else left = mid + 1;
        }
        left = 0;
		int tmp = middle;
		while (left <= middle)
		{
			int mid = (left + middle) / 2;
			int n = mountainArr.get(mid);
			if (n == target) return mid;
			if (n > target) middle = mid - 1;
			else left = mid + 1;
		}
		while (tmp <= right)
		{
			int mid = (tmp + right) / 2;
			int n = mountainArr.get(mid);
			if (n == target) return mid;
			if (n > target) tmp = mid + 1;
			else right = mid - 1;
		}
		return -1;
	}
};

最后一题1096. Brace Expansion II
Leetcode进阶之路——Weekly Contest 142_第4张图片
这道题比较“精简”的写法应该是递归:

  • 每遇到一个左大括号且其处于当前string的最外层,则重置start为左大括号后一位
  • 当遇到与上述左大括号配对的右大括号时,对该内部string重新调用函数,直至无括号嵌套

看了discuss后,C++代码普遍较为"冗余",而python由于其对数据存储的灵活性,则可以写得相对精简,且其itertools.product也可以较为方便(暴力)地对数组内元素进行两两组合,这里贴上Python3 Clear and Short Recursive Solution的代码作为学习,若C++也有较为简洁的写法, 还望指教

class Solution:
    def braceExpansionII(self, expression: str) -> List[str]:
        groups = [[]]
        level = 0
        for i, c in enumerate(expression):
            if c == '{':
                if level == 0:
                    start = i+1
                level += 1
            elif c == '}':
                level -= 1
                if level == 0:
                    groups[-1].append(self.braceExpansionII(expression[start:i]))
            elif c == ',' and level == 0:
                groups.append([])
            elif level == 0:
                groups[-1].append([c])
        word_set = set()
        for group in groups:
            word_set |= set(map(''.join, itertools.product(*group)))
        return sorted(word_set)

你可能感兴趣的:(leetcode,C++,C++,leetcode)