数组题目

  • 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
class Solution {
public:
    const int MaxLength = 10;
    char* StrCombine1 = new char[MaxLength*2+1];
    char* StrCombine2 = new char[MaxLength*2+1];
    
    string PrintMinNumber(vector<int> numbers) {
        string str;
        if(numbers.size()==0)
            return str;
        sort(numbers.begin(),numbers.end(),cmp);
        for(int i = 0;i<numbers.size();i++)
        {
            str+= to_string(numbers[i]);
        }
        return str;
    }
    static bool cmp(int a,int b)
    {
        string A = to_string(a)+to_string(b);
        string B = to_string(b)+to_string(a);
        return A<B;
    }
};
  • 在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
class Solution {
public:
    int InversePairs(vector<int> data) {
        if(data.empty())
            return 0;
        int len = data.size();
        vector<int> copy;
        int i =0;
       for(int i=0;i<len;i++)
           copy.push_back(data[i]);
        long long count = InversePairsCore(data, copy,0,len-1);
        return count%1000000007;
    }
     long long InversePairsCore(vector<int>& data,vector<int>& copy,int start,int end)
    {
        if(start==end)
        {
            copy[start] = data[start];
            return 0;
        }
        int length = (end-start)/2;
         
        long long left = InversePairsCore(copy,data,start,start+length);
        long long right = InversePairsCore(copy,data,start+length+1,end);
        
        int i = start+length;
        int j = end;
        
        int index = end;
        long count = 0;
        
        while(i>=start && j>=start+length+1)
        {
            if(data[i]>data[j])
            {
                copy[index--] = data[i--];
                count+=j-start-length;
            }
            else{
                copy[index--] = data[j--];
            }
        }
        
        for(;i>=start;i--)
        {
            copy[index--] = data[i];
        }
          for(;j>=start+length+1;j--)
        {
            copy[index--] = data[j];
        }
         
         return left+right+count;
    }
};
  • 一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
class Solution {
public:
    void FindNumsAppearOnce(vector<int> data, int* num1,int *num2) {
        map<int,int> countmap;
        size_t i = 0;
        for(;i<data.size();i++)
        {
            countmap[data[i]]++;
        }
        map<int,int>::iterator it = countmap.begin();
        int j = 0;
        while(it!=countmap.end())
        {
            if(it->second==1)
            {
                j++;
                *num1 = (it->first);
            }
            if(j==1&&it->second==1)
                *num2 = (it->first);
            ++it;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/qq_36474990/article/details/80877989
今日推荐