算法提升(C++) 2020-10-26 ---- 2020-11-1

这是一篇关于C++算法提升的文章,涵盖了面试题目和编程挑战,包括动物收容所问题、七进制数转换、链表操作、数组排序、滑动窗口最大值等。文章内容丰富,适合提升编程技巧和准备面试。
摘要由CSDN通过智能技术生成

其他

2020-10-26

面试题 03.06. 动物收容所

class AnimalShelf {
private:
    queue<int> Cat;
    queue<int> Dog;
public:
    AnimalShelf() {}
    void enqueue(vector<int> animal) {
        if(animal[1] == 0) Cat.push(animal[0]);
        else Dog.push(animal[0]);
    }
    vector<int> dequeueAny() {
        if(Dog.empty() && Cat.empty()) return {-1,-1};
        else if(Dog.empty() && !Cat.empty()){
            int n = Cat.front();
            Cat.pop();
            return {n,0};
        } else if(Cat.empty() && !Dog.empty()){
            int n = Dog.front();
            Dog.pop();
            return {n,1};
        }else{
            if (Cat.front() < Dog.front()) //动物编号:猫 < 狗 猫先出
            {
                int n = Cat.front();
                Cat.pop();
                return {n,0};
            }else {
                int n = Dog.front();
                Dog.pop();
                return {n,1};
            }
        }
    }
    
    vector<int> dequeueDog() {
        if(Dog.empty()) return {-1,-1};
        else {
            int n = Dog.front();
            Dog.pop();
            return {n,1};
        }
    }
    
    vector<int> dequeueCat() {
        if(Cat.empty()) return {-1,-1};
        else {
            int n = Cat.front();
            Cat.pop();
            return {n,0};
        }
    }
};

七进制数

class Solution {
public:
    string convertToBase7(int num) {
        if(num == 0) return "0";
        string res = "";
        int flag = 0;
        if(num < 0) {num = -num;flag=1;}
        while(num) {
            res += num%7+'0';
            num/=7;
        }
        if(flag == 1) res+="-";
        reverse(res.begin(),res.end());
        return res;
    }
};

LCP 01. 猜数字

class Solution {
public:
    int game(vector<int>& guess, vector<int>& answer) {
        int res = 0;
        for(int i = 0; i < guess.size(); i++) if(guess[i] == answer[i]) res++;
        return res;
    }
};

LCP 06. 拿硬币

class Solution {
public:
    int minCount(vector<int>& coins) {
        int ans =0;
        for(int i = 0; i < coins.size(); i++) {
            ans += coins[i]/2;
            if(coins[i]%2 == 1) ans+=1;
        }
        return ans;
    }
};

LCP 07. 传递信息

class Solution {
public:
    int numWays(int n, vector<vector<int>>& relation, int k) {
        int dp[10][15];
        memset(dp,0,sizeof(dp));
        dp[0][0] = 1;
        for(int i = 0; i < k; i++) {
            for(auto r:relation) {
                dp[i+1][r[1]] += dp[i][r[0]];
            }
        }
        return dp[k][n-1];
    }
};

LCP 11. 期望个数统计

class Solution {
public:
    int expectNumber(vector<int>& scores) {
        set<int> s;
        for(int ss:scores) s.insert(ss);
        return s.size(); 
    }
};

LCP 17. 速算机器人

class Solution {
public:
    int calculate(string s) {
        int x = 1;
        int y = 0;
        for(auto ss:s) {
            if(ss == 'A') {
                x = 2*x+y;
            } else {
                y = 2*y+x;
            }
        }
        return x+y;
    }
};

LCP 18. 早餐组合

class Solution {
public:
    int breakfastNumber(vector<int>& staple, vector<int>& drinks, int x) {
        sort(staple.begin(),staple.end());
        sort(drinks.begin(),drinks.end());
        int j = drinks.size()-1;
        int ans = 0;
        for (int i = 0; i < staple.size(); i++) {
            while (j >= 0 && staple[i] + drinks[j] > x) j--;
            if (j == -1) break;
            ans += j + 1;
            ans %= (int)(1e9+7);
        }
        return ans;
    }
};

LCP 22. 黑白方格画

class Solution {
public:
    int C(int n,int k){
        if(k==0 ||n==1||n==k)
            return 1;
        return C(n-1,k-1)+C(n-1,k);
    }
    int paintingPlan(int n, int k) {
        int ans=0;
        if(n*n==k)
            return 1;
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                if(i*j==n*n-k){
                    ans+=C(n,i)*C(n,j);
                }
            }
        }

        return ans;
    }

};

1042. 不邻接植花

class Solution {
public:
    vector<int> gardenNoAdj(int N, vector<vector<int>>& paths) {
        vector<int> tmp[N];
        for(int i = 0; i < paths.size(); i++) {
            tmp[paths[i][0]-1].push_back(paths[i][1]-1);  
            tmp[paths[i][1]-1].push_back(paths[i][0]-1);
        }
        vector<int> answer(N,0);//初始化全部未染色
        for(int i=0; i<N; i++){
            set<int> color{1,2,3,4};
            for (int j=0; j<tmp[i].size(); j++){
                color.erase(answer[tmp[i][j]]);//把已染过色的去除
            }
            answer[i]=*(color.begin());//染色
        }
        return answer;
    }
};

剑指 Offer 25. 合并两个排序的链表

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* head = new ListNode(1);
        ListNode* ret = head;
        while (l1 != NULL && l2 != NULL) {
            if (l1->val < l2->val) {
                head->next = l1;
                l1 = l1->next;
            } else {
                head->next = l2;
                l2 = l2->next;
            }
            head = head->next;
        }
        head->next = l1 == NULL ? l2 : l1;
        return ret->next;
    }
};
2020-10-27

剑指 Offer 21. 调整数组顺序使奇数位于偶数前面

class Solution {
public:
    vector<int> exchange(vector<int>& nums) {
        int n = nums.size();
        if(n==0) return {};
        vector<int> res(n);
        int j=0,i=0;
        int tmp =0;
        while(1){
            if(nums[tmp]%2==1) {res[i]=nums[tmp];tmp++;i++;}
            else {res[n-1-j] = nums[tmp];tmp++;j++;}
            if(tmp==n) break;
        }
        return res;
    }
};

剑指 Offer 65. 不用加减乘除做加法

class Solution {
public:
    int add(int a, int b) {
int sum,carry;
        while(b){
            sum=a^b;
            carry=(unsigned int)(a&b)<<1;
            a=sum;
            b=carry;
        }
        return a;
    }
};

剑指 Offer 57. 和为s的两个数字

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int front=0,end=nums.size()-1;
        while(front<end){
            int s=nums[front] + nums[end];
            if(s==target) return {nums[front],nums[end]  };
            else if(s > target) end--;
            else front++;
        }
        return {-1,-1};
    }
};

剑指 Offer 39. 数组中出现次数超过一半的数字 LCOF
169. Majority Element
#面试题 17.10 主要元素

class Solution {
public:
    int majorityElement(vector<int>& nums) {
         map<int, int> match;

        int len = nums.size(), res = 0;

        if(len == 1 || len == 2){

            return nums[0];

        }

        for(int i = 0; i < len; ++i){

            match[nums[i]] ++;

            if(match[nums[i]] > (len / 2)){

                res = nums[i];

                break;

            }

        }

        return res;
    }
};

剑指 Offer 05. 替换空格 LCOF

class Solution {
public:
    string replaceSpace(string s) {
        string res;
        for(auto ss :s) {
            if(ss==' ') {
                res+= "%20";
                continue;
             }
            res+=ss;
        }
        return res;
    }
};

剑指 Offer 62 圆圈中最后剩下的数字


class Solution {
public:
    int lastRemaining(int n, int m) {
        if(n==1) return 0;
        int x = lastRemaining(n-1,m);
        return (m+x)%n;
    }
};

剑指 Offer 61 扑克牌中的顺子

class Solution {
public:
    bool isStraight(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        int zero = 0;
        for(int i = 0; i < 4; i++)  {
            if(nums [i] == 0)  {
                zero++;
                continue;
            }
            if(nums [i] == nums[i+1] ) return false;
            zero -= nums[i+1]-nums[i]-1;
        }
        return zero>=0?true:false;
    }
};

面试题 16.11 跳水板

class Solution {
public:
    vector<int> divingBoard(int shorter, int longer, int k) {
        if(k==0) return {};
        if(shorter == longer) return {shorter*k};
        vector<int> res(k+1);
        for(int i = 0;i <=k;i++) res[i] = shorter * (k-i)+longer*i;
        return res;
    }
};
2020-10-18

剑指 Offer 59 - I. 滑动窗口的最大值

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        vector<int> ans;
	   deque<int> deq;
	   for (int i = 0; i != nums.size(); ++i)
	   {
		   while (!deq.empty() && nums[deq.back()] <= nums[i])
			   deq.pop_back();
		   while (!deq.empty() && deq.front() < i - k + 1)
			   deq.pop_front();
		   deq.push_back(i);
		   if (i >= k - 1)  ans.push_back(nums[deq.front()]);
	    }
	    return ans;
    }
};

剑指 Offer 40. 最小的k个数

class Solution {
public:
    vector<int> getLeastNumbers(vector<int>& arr, int k) {
        vector<int> res;
        sort(arr.begin(),arr.end());
        for(int i = 0; i < k; i++) {
            res.push_back(arr[i]);
        }
        return res;
    }
};

面试题 03.01. 三合一


class TripleInOne {
private:
    vector<int> s;
    int stackSize;
    int spointer[3];
public:
    TripleInOne(int stackSize) {
        s = vector<int>(stackSize*3, 0);
        this->stackSize = stackSize; 
        spointer[0] = 0;
        spointer[1] = stackSize;
        spointer[2] = stackSize*2;
    }
    
    //然后将元素push进去的话我们首先看有没有溢出的
    void push(int stackNum, int value) {
        if(spointer[stackNum] < (stackNum+1)*stackSize){
            s[spointer[stackNum]++] = value;
        }
    }
    
    //这里的pop的话就看是否有元素让你pop出来,没有的话就返回-1
    int pop(int stackNum) {
        int res = -1;
        if(spointer[stackNum] > (stackNum)*stackSize){
            res = s[--spointer[stackNum]];
        }
        return res;
    }
    
    //peek的操作和上面的pop操作类似,不同的点就是我们不需要把指针往后退一步
    int peek(int stackNum) {
        int res = -1;
        if(spointer[stackNum] > (stackNum)*stackSize){
            res = s[spointer[stackNum]-1];
        }
        return res;
    }
    
    //看看是不是空的话我们就看每个栈的指针是不是在原来的初始位置上
    bool isEmpty(int stackNum) {
        return spointer[stackNum] == stackNum*stackSize;
    }
};

LCP 02. 分式化简

class Solution {
public:
    vector<int> fraction(vector<int>& cont) {
        int high = 1, low = cont[cont.size()-1];
        for(int i = cont.size() - 2; i >= 0; --i){
            high += low * cont[i];
            swap(low, high);
        }
        return vector<int>{low, high};
    }
};

面试题 08.10. 颜色填充

class Solution {
public:
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor)
    {
        if (newColor == image[sr][sc]) return image; //这个条件是防止无限递归
        int old = image[sr][sc];
        image[sr][sc] = newColor;
        digui(image, sr - 1, sc, newColor, old);
        digui(image, sr + 1, sc, newColor, old);
        digui(image, sr, sc - 1, newColor, old);
        digui(image, sr, sc + 1, newColor, old);
        return image;
    }
    void digui(vector<vector<int>>& image, int sr, int sc, int &newColor, int &old)
    {
        if (sr >= 0 && sc >= 0 && sr < image.size() && sc < image[0].size() && image[sr][sc] == old)
        {
                image[sr][sc] = newColor;
                digui(image, sr - 1, sc, newColor, old);
                digui(image, sr + 1, sc, newColor, old);
                digui(image, sr, sc - 1, newColor, old);
                digui(image, sr, sc + 1, newColor, old);
        }
    }
};

根据数字二进制下 1 的数目排序

class Solution {
public:
        vector<int> sortByBits(vector<int>& arr)
        {
            sort(arr.begin(), arr.end(), cmp);
            return arr;
        }
        static bool cmp(int a, int b)
        {
            int bca = bitCount(a), bcb = bitCount(b);
            return (bca == bcb) ? a < b : bca < bcb;
        }
        static int bitCount(int n)
        {
            int cnt = 0;
            while (n > 0)
            {
                if (n & 1)
                    cnt++;
                n >>= 1;
            }
            return cnt;
        }
};

删除某些元素后的数组均值

class Solution {
public:
    double trimMean(vector<int>& arr) {
         int len=arr.size();
        int del=len/20;
        int sum=0;
        sort(arr.begin(),arr.end());
        for(int i=del;i<len-del;i++){
            sum+=arr[i];
        }
        return sum/(len-del*2.0);
    }
};

相对名次

class Solution {
public:
    string tostr(int n){
        if(n==1) return "Gold Medal";
        if(n==2) return "Silver Medal";
        if(n==3) return "Bronze Medal";
        return to_string(n);
    }
    vector<string> findRelativeRanks(vector<int>& nums) {
        int n = nums.size();
        vector<string> result(n);
        map<int, int> m;
        for (int i=0; i<n; i++) m[nums[i]] = i;
        for (const auto &it:m) {
            result[it.second] = tostr(n--);
        }
        return result;
    }
};
2020-10-29

Nim 游戏

class Solution {
public:
    bool canWinNim(int n) {
		return (n%4!=0);
    }
};

最长特殊序列 Ⅰ

class Solution {
public:
    int findLUSlength(string a, string b) {
		return a==b?-1:max(a.size(),b.size());
    }
};

Fizz Buzz

class Solution {
public:
    vector<string> fizzBuzz(int n) {
		vector<string> res;
        for(int i = 0; i<n;i++) {
            if((i+1)%3==0&&(i+1)%5==0) res.push_back("FizzBuzz");
            else if((i+1)%3==0)res.push_back("Fizz");
            else if((i+1)%5==0) res.push_back("Buzz");
            else res.push_back(to_string(i+1));
    
        }
        return res;
    }
};

构造矩形

class Solution {
public:
    vector<int> constructRectangle(int area) {
       int w=sqrt(area);
        while(area%w!=0) w--;
        return {area/w,w};
    }
};

二进制手表

class Solution {
public:
    vector<string> readBinaryWatch(int num) {
		vector<string> res;
        for(int i =0;i < 12;i++) {
            for(int j = 0; j < 60; j++)  {
                if(count(i)+count(j) == num) res.push_back(to_string(i)+":"+(j<10?("0"+to_string(j)):to_string(j)));
            }
        }
        return res;
    }
    int count(int n) {
        int res = 0;
        while(n!=0)  {
            if(n&1)   res++;
              n >>= 1;
        }
        return res;
    }
};

旋转字符串

class Solution {
public:
    bool rotateString(string A, string B) {
		 return A.size() == B.size() && (A + A).find(B) != string::npos;
    }
};

设计停车系统

class ParkingSystem {
    private:
       int Pbig = 0;
       int Pmedium = 0;
       int Psmall = 0;
public:

    ParkingSystem(int big, int medium, int small) {
        Pbig = big;
        Pmedium = medium;
        Psmall = small;
    }
    
    bool addCar(int carType) {
        if(carType == 1) {
            if(Pbig!=0) {
                Pbig--;
                return true;
            }else return false;
        }else if(carType == 2) {
            if(Pmedium!=0) {
                Pmedium--;
                return true;
            }else return false;
        }else{
            if(Psmall!=0) {
                Psmall--;
                return true;
            }else return false;
        }
    }
};

设计哈希集合

class MyHashSet {
public:
    /** Initialize your data structure here. */
    bool st[1000010] = {false};
    MyHashSet() {

    }
    
    void add(int key) {
       st[key] = true;
    }
    
    void remove(int key) {
        st[key] = false;
    }
    
    /** Returns true if this set contains the specified element */
    bool contains(int key) {
        return st[key];
    }
};

设计哈希映射

class MyHashMap {
public:
    vector<int> map=vector<int>(1e6,-1);
    /** Initialize your data structure here. */
    MyHashMap() {

    }
    
    /** value will always be non-negative. */
    void put(int key, int value) {
        map[key] = value;
    }
    
    /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
    int get(int key) {
        return map[key];
    }
    
    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    void remove(int key) {
        map[key] = -1;
    }
};

剑指 Offer 60. n个骰子的点数

class Solution {
public:
    vector<double> twoSum(int n) {
        const double D16 = 1.0 / 6.0;
        vector<double> res(6*n+1, 0.0);
        for (int i = 1; i <= 6; i++) {
            res[i] = D16;
        }
        for (int i = 2; i <= n; i++) {
            for (int j = 6*i; j >= i; j--) {
                res[j] = 0;
                for (int k = j-1; k >= i-1 && k >= j-6; k--) {
                    res[j] += (res[k] * D16);
                }
            }
        }
        return vector<double>(res.begin()+n, res.end());
    }
};
2020-10-31

密钥格式化

class Solution {
public:
    string licenseKeyFormatting(string s, int k) {
        reverse(s.begin(), s.end());
        string t, res;
        for(int i=0; i<s.length(); i++){
            if(t.length() == k){
                res+=t;
                res+='-';
                t.clear();
            }
            if(isalnum(s[i])){
                if(s[i]-'a' < 26 && s[i]-'a'>=0){
                    t+=(s[i]-32);
                }else{
                    t+=s[i];
                }
            }
        }
        res+=t;
        if(res[res.length()-1] =='-'){
            res.erase(res.length()-1);
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

移动石子直到连续

class Solution {
public:
    vector<int> numMovesStones(int a, int b, int c) {
        if(b < a) swap(a, b);
        if(c < a) swap(a, c);
        if(c < b) swap(b, c);
        if(a+1 == b && b+1 == c) return {0,0};
        return {(c - b <= 2 || b - a <= 2)?1:2,(c-1-b)+(b-1-a)};
    }
};

日期之间隔几天

static int months[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
class Solution {
private:
    bool isLeap(int year) {
        return year % 100 && year % 4 == 0 || year % 400 == 0;
    }
    int getDay(string date) {
        int year, month, day;
        sscanf(date.c_str(), "%d-%d-%d", &year, &month, &day);
        int days = 0;
        for (int y = 1971; y < year; y ++) {
            days += isLeap(y) + 365;
        }
        for (int m = 1; m < month; m ++) {
            if (m == 2) days += isLeap(year) + 28;
            else
                days += months[m];
        }
        return days + day;

    }
public:
    int daysBetweenDates(string date1, string date2) {
        return abs(getDay(date1) - getDay(date2));
    }
};

括号的最大嵌套深度

class Solution {
public:
    int maxDepth(string s) {
        if(s.length() == 1) return 0;
        int depth = 0, left = 0;
        for(int i=0; i<s.length(); ++i)
        {
            if(s[i] == '(')
            {
                left ++;
                if(left > depth) depth = left;
            }
            else if(s[i] == ')')
            {
                left --;
            }
            else ;
        }
        return depth;
    }
};

字符的最短距离

class Solution {
public:
    vector<int> shortestToChar(string S, char C) {
        vector<int> tmp;
        int i = 0;
        for(auto ss:S) {
            if(ss == C){tmp.push_back(i);} 
            i++;
        }
        int j = 0;
        int left = -1;
        int right = tmp[j];
        vector<int> res;
        for(int i = 0; i < S.size(); i++) {
            if(left == -1) {res.push_back(abs(right-i));}
            else res.push_back(min(abs(left-i),abs(right-i))); 
            if(right == i && j<tmp.size()-1) {
                left = right;
                right = tmp[++j];
            }
        }
        return res;
    }
};

剑指 Offer 57 - II. 和为s的连续正数序列

class Solution {
public:
    vector<vector<int>> findContinuousSequence(int target) {
        int i = 1; // 滑动窗口的左边界
        int j = 1; // 滑动窗口的右边界
        int sum = 0; // 滑动窗口中数字的和
        vector<vector<int>> res;
        while (i <= target / 2) {
            if (sum < target) {
                // 右边界向右移动
                sum += j;
                j++;
            } else if (sum > target) {
                // 左边界向右移动
                sum -= i;
                i++;
            } else {
                // 记录结果
                vector<int> arr;
                for (int k = i; k < j; k++) {
                    arr.push_back(k);
                }
                res.push_back(arr);
                // 左边界向右移动
                sum -= i;
                i++;
            }
        }

        return res;
    }
};

写字符串需要的行数

class Solution {
public:
    vector<int> numberOfLines(vector<int>& widths, string S) {
        int lines = 1, width = 0;
        for (char c: S) {
            int w = widths[c - 'a'];
            width += w;
            if (width > 100) {
                lines++;
                width = w;
            }
        }

        return {lines, width};
    }
};

两个相同字符之间的最长子字符串

class Solution {
public:
    int maxLengthBetweenEqualCharacters(string s) {
        vector<int> start(26, -1);
        int maxlen = -1;
        for(int i = 0; i < s.size(); ++i) 
        {
            int idx = s[i]-'a';
            if(start[idx]== -1)// -1 表示还未出现过
                start[idx] = i;
            else//已经出现过了,做差求长度,取最大
                maxlen = max(maxlen, i-start[idx]-1);
        }
        return maxlen;

    }
};

最后一块石头的重量

class Solution {
public:
    int lastStoneWeight(vector<int>& stones) {
       if(stones.size()<=1)
        {
            return stones[0];
        }
        sort(stones.begin(),stones.end(),greater<int>());
        int len=stones.size();
        while(len--)
        {
            stones[0]=stones[0]-stones[1];
            stones[1]=0;
            sort(stones.begin(),stones.end(),greater<int>());
        }
        return stones[0];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
城市应急指挥系统是智慧城市建设的重要组成部分,旨在提高城市对突发事件的预防和处置能力。系统背景源于自然灾害和事故灾难频发,如汶川地震和日本大地震等,这些事件造成了巨大的人员伤亡和财产损失。随着城市化进程的加快,应急信息化建设面临信息资源分散、管理标准不统一等问题,需要通过统筹管理和技术创新来解决。 系统的设计思路是通过先进的技术手段,如物联网、射频识别、卫星定位等,构建一个具有强大信息感知和通信能力的网络和平台。这将促进不同部门和层次之间的信息共享、交流和整合,提高城市资源的利用效率,满足城市对各种信息的获取和使用需求。在“十二五”期间,应急信息化工作将依托这些技术,实现动态监控、风险管理、预警以及统一指挥调度。 应急指挥系统的建设目标是实现快速有效的应对各种突发事件,保障人民生命财产安全,减少社会危害和经济损失。系统将包括预测预警、模拟演练、辅助决策、态势分析等功能,以及应急值守、预案管理、GIS应用等基本应用。此外,还包括支撑平台的建设,如接警中心、视频会议、统一通信等基础设施。 系统的实施将涉及到应急网络建设、应急指挥、视频监控、卫星通信等多个方面。通过高度集成的系统,建立统一的信息接收和处理平台,实现多渠道接入和融合指挥调度。此外,还包括应急指挥中心基础平台建设、固定和移动应急指挥通信系统建设,以及应急队伍建设,确保能够迅速响应并有效处置各类突发事件。 项目的意义在于,它不仅是提升灾害监测预报水平和预警能力的重要科技支撑,也是实现预防和减轻重大灾害和事故损失的关键。通过实施城市应急指挥系统,可以加强社会管理和公共服务,构建和谐社会,为打造平安城市提供坚实的基础。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值