NC101 压缩字符串(一) 牛客题霸 and NC257 求1+2+3+...+n 牛客题霸 and CPP21 C++冒泡排序 牛客

112 阅读1分钟

NC101 压缩字符串(一) 牛客题霸

双指针模拟

在这里插入图片描述

class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param param string字符串
     * @return string字符串
     */
    string compressString(string param) {
        // write code here
        // 双指针
        int lenP = param.size(); // 获取原字符串的大小
        string res = ""; // 初始化结果字符串
        int j = 0;    // j指针初始化
        for (int i = 0;;) {
            int t = 0; // 每一轮当前这种字符的数量为0
            // 若i指针与j指针指向的字符相等,且j指针没有超过原字符串的大小
//             说明这种种类的字符有一个了,就++
            while (param[i] == param[j] && j < lenP) {
                j++;
                t++;
            }
            // 跳出循环说明遇到不相等的字符了,就往结果字符串中加入
            res.push_back(param[i]);
            // 若这种字符的数量比1多,就把数量加入,否则1就是不显示
            if (t > 1) res += to_string(t);
            i = j;    // 把i指针往后挪到j指针的位置,重新定位
            // 说明原字符串已经走完了
            if (j >= lenP) break;
        }
        return res;
    }
};

NC257 求1+2+3+...+n 牛客题霸

等差数列求和公式

NC

class Solution {
public:
    int Sum_Solution(int n) {
        // 等差数列公式
        return (1 + n) * (n - 1 + 1) / 2;
    }
};

CPP21 C++冒泡排序 牛客

冒泡排序的思想:

关键就是“冒泡”,例如:从小到大排序,那意味着,我要将“大的泡泡”往上面浮,那么怎么浮呢?示意图如下: 在这里插入图片描述 在这里插入图片描述

#include <iostream>
using namespace std;

int main() {

    int arr[6] = { 0 };
    int len = sizeof(arr) / sizeof(int); // 待排序数组的长度
    
    for (int i = 0; i < len; i++) {
        cin >> arr[i];
    }
    
    // write your code here......
    // 六个数字 5轮
    for (int i = 0;i < len - 1; ++i) {
    	// 第一轮:比较5次
    	// ...
        for (int j = 0; j < len - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(arr[j], arr[j + 1]);
            }
        }
    }
    
    for (int i = 0; i < len; ++i) {
        cout << arr[i] << " ";
    }
    return 0;
}