2023-08-23力扣每日一题

链接:

1782. 统计点对的数目

题意:

给n个点和m条无向边(可重复),q个查询

定义edge[a]为一个点是a的边数量,定义ret[a,b]edge[a]+edge[b]-(a与b的边)

q个查询q个答案,第i次查询值val[i],求所有的1<=a条件下有多少ret[a,b]>val[i]

解:

TLE卡47了

看了评论区用空间换时间,双指针

实际代码:

class Solution {
public:
    typedef pair pii;
vector countPairs(int n, vector>& edges, vector& queries)
{
	vectoredgeNum(n+1);//记录edge[a]
	mapedgePair;
	for(auto edge:edges)
	{
		if(edge[0]>edge[1]) swap(edge[0],edge[1]);
		edgeNum[edge[0]]++;
		edgeNum[edge[1]]++;
		edgePair[{edge[0],edge[1]}]++;//记录(a与b的边)
	}
	vectorans;	
	vectoredgeNS(edgeNum);	
	sort(edgeNS.begin(),edgeNS.end());//空间换时间 排序
	
	for(auto querie:queries)
	{
		int temp=0;
		int left=1,right=n;
		while(leftquerie && s-Pair.second<=querie) temp--;
		}
		ans.push_back(temp);
	}
	return ans;
}
};

限制:

  • 2 <= n <= 2 * 104
  • 1 <= edges.length <= 105
  • 1 <= ui, vi <= n
  • ui != vi
  • 1 <= queries.length <= 20
  • 0 <= queries[j] < edges.length

你可能感兴趣的:(力扣每日一题,leetcode,c++)