zoukankan      html  css  js  c++  java
  • c++ 有swap函数

    这是剑指offer数组中重复的数字那个题,直接使用的swap函数

    class Solution {
    public:
        // Parameters:
        //        numbers:     an array of integers
        //        length:      the length of array numbers
        //        duplication: (Output) the duplicated number in the array number
        // Return value:       true if the input is valid, and there are some duplications in the array number
        //                     otherwise false
        bool duplicate(int numbers[], int length, int* duplication) {
            if(length <= 0){
                *duplication = -1;
                return false;
            }
            int start = 0;
            while(start < length){
                if(numbers[start] == numbers[numbers[start]] && numbers[start] != start){
                    *duplication = numbers[start];
                    return true;
                }
                if(start == numbers[start]){
                    start++;
                    continue;
                }
                int index = numbers[start];
                while(numbers[start] != numbers[index]){
                    swap(numbers[start],numbers[index]);
                    index = numbers[start];
                }
            }
            *duplication = -1;
            return false;
        }
    };

    字符串的全排列也用到了swap

    class Solution {
    public:
        vector<string> Permutation(string str) {
            if(str.size() == 0)
                return ans;
            length = str.size();
            int begin = 0;
            Permutation(str,begin);
            //res.clear();
            set<string>::iterator it;
            for (it = res.begin(); it != res.end(); ++it)
                ans.push_back(*it);
            return ans;
        }
        void Permutation(string str,int begin){
            if(begin == length){
                res.insert(str);
                return;
            }
            for(int i = begin;i < length;i++){
                swap(str[begin],str[i]);
                Permutation(str,begin+1);
                swap(str[begin],str[i]);
            }
        }
        set<string> res;
        vector<string> ans;
        int length = 0;
    };
  • 相关阅读:
    PyCharm 2020 激活到 2100 年
    PyTorch-22 学习 PyTorch 的 Examples
    机器视觉的主要研究内容和细分方向(超全超赞)
    CVPR 2020 全部论文 分类汇总和打包下载
    2020年,加油鸭
    SpiningUP 强化学习 中文文档
    大学C语言基础——30天挑战PAT甲级(一)
    明天提交辞职报告
    要开始新的技术之旅了
    记忆是件奇怪的东西
  • 原文地址:https://www.cnblogs.com/ymjyqsx/p/9551811.html
Copyright © 2011-2022 走看看