刷题总结#6

来源:互联网 发布:淘宝一元云购是真的吗 编辑:程序博客网 时间:2024/06/05 01:09

#378. Kth Smallest Element in a Sorted Matrix
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,

return 13.
这道题我们可以想成取k-1次最小值。
用拓扑的思想。我们先将第一排的数放到最小堆里面,然后每取出一个数,就将它对应的下面一个数加入最小堆里面。【它右边一个数,由它右边这个数的上面一个数控制。】
1.注意cmp的写法,最小堆是return a>b;
2.priority_queue< pair < int,pair < int,int>>,vector < pair < int,pair < int,int >>>,cmp>pq;
第一个参数数据类型,第二个数据的容器,第三个是比较函数。
struct cmp
{
bool operator()(const pair < int,pair < int,int>>& a, const pair < int,pair < int,int>>& b)
{
return a.first>b.first;
}
};
public:
int kthSmallest(vector < vector < int>>& matrix, int k) {

    int n=matrix.size();    priority_queue<pair<int,pair<int,int>>,vector<pair<int,pair<int,int>>>,cmp>pq;    for(int i=0;i<n;i++)    {        pq.push(make_pair(matrix[0][i],make_pair(0,i)));    }    pair<int,pair<int,int>> t;    //int x=k-1;    while(k--)    {         t=pq.top();         pq.pop();        if(t.second.first!=n-1)        {            pq.push(make_pair(matrix[t.second.first+1][t.second.second],make_pair(t.second.first+1,t.second.second)));        }        //k--;    }    return t.first;}

#12. Integer to Roman
记住就行
public static String intToRoman(int num) {
String M[] = {“”, “M”, “MM”, “MMM”};
String C[] = {“”, “C”, “CC”, “CCC”, “CD”, “D”, “DC”, “DCC”, “DCCC”, “CM”};
String X[] = {“”, “X”, “XX”, “XXX”, “XL”, “L”, “LX”, “LXX”, “LXXX”, “XC”};
String I[] = {“”, “I”, “II”, “III”, “IV”, “V”, “VI”, “VII”, “VIII”, “IX”};
return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10];
}

#318. Maximum Product of Word Lengths
Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.
Given [“abcw”, “baz”, “foo”, “bar”, “xtfn”, “abcdef”]
Return 16
The two words can be “abcw”, “xtfn”.

这道题是叫我们对每个单词,找出与之含有单词不同的那些单词,然后计算最大的乘积。
特点在于找不同的单词
把 a-z看作每一个位,则一个单词对应一个26位的int。有字母则为1。
通过&操作看是否单词有相同的位。
vectorvalue(words.size(),0);
for(int i=0;i < words.size();i++)
{

        for(int j=0;j<words[i].length();j++)        {            value[i]|=1<<(words[i][j]-'a');        }    }    int ans=0;    for(int i=0;i<value.size();i++)    {        for(int j=i+1;j<value.size();j++)        {            if((value[i]&value[j])==0)            {                if(words[i].length()*words[j].length()>ans)                ans=words[i].length()*words[j].length();            }        }    }    return ans;

注意的是if((value[i]&value[j])==0) 如果写成if(value[i]&value[j]==0)是不对的。先计算==

0 0