排序算法练习题

现给出一个序列a,其中元素的个数为n,要求将它们按从小到大的顺序排序。

冒泡排序

#include <iostream>
using namespace std;

int main()
{
	int a[10] = {3,4,1,5,2};
	for(int i = 1;i <= 4; i++){
		for(int j = 0; j < 5 - i; j++){
			if(a[j] > a[j + 1]){
				int temp = a[j];
				a[j] = a[j + 1];
				a[j + 1] = temp;
			}
		}
	}
	for(int i = 0; i < 5; i++){
		cout << a[i] << " ";
	}
	cout << endl;
	return 0;
}

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。

示例 1:

输入: s = "anagram", t = "nagaram"
输出: true
示例 2:

输入: s = "rat", t = "car"
输出: false
说明:
你可以假设字符串只包含小写字母。

解法一:散列

class Solution {
public:
    bool isAnagram(string s, string t) {
        int hashTable[26] = {0};
        int len1 = s.length();
        int len2 = t.length();
        if(len1 != len2){
            return false;
        }
        else{
            for(int i = 0; i < len1; i++){
                hashTable[s[i] - 'a']++;
            }
            for(int i = 0; i < len2; i++){
                hashTable[t[i] - 'a']--;
            }
            for(int i = 0; i < 26; i++){
                if(hashTable[i] != 0){
                    return false;
                }
            }
            return true;
        }
    }
};

解法二:排序算法

class Solution {
public:
    bool isAnagram(string s, string t) {
        //排序算法
        int len1 = s.size();
        int len2 = t.size();
        if(len1 != len2){
            return false;
        }
        else{
            sort(s.begin(),s.end());
            sort(t.begin(),t.end());
            return s == t;
        }
    }
};

#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
	int n;
	while(cin >> n){
		int hashTable[1001] = {0};
		int a[101];
		int b[101];
		for(int i = 0; i < n; i++){
			cin >> a[i];
			hashTable[a[i]]++;
		}

		int j = 0;
		for(int i = 0; i < 1001; i++){
			if(hashTable[i] != 0){
				b[j++] = i;
			}
		}
		sort(b, b + j);
		cout << j << endl;
		for(int i = 0; i < j; i++){
			cout << b[i] << " ";
		}
		cout << endl;
	}
	return 0;
}

#include <iostream>
#include <algorithm>
using namespace std;

int m;

struct Student{
	int id;
	int score[101];
	bool isEnter;
}stu[1001];

bool cmp(Student a, Student b){
	int i = 0;
	while(i < m){
		if(a.score[i] != b.score[i]){
			return a.score[i] > b.score[i];
		}
		else{
			i++;
		}
	}
}

int main()
{
	int n,k;
	while(cin >> n >> m >> k){
		for(int i = 0; i < n; i++){  //输入n个学生成绩 
			stu[i].id = i + 1;  //学号 
			stu[i].isEnter = true;
			for(int j = 0; j < m; j++){
				cin >> stu[i].score[j];
				if(stu[i].score[j] < 85){
					stu[i].isEnter = false;
				}
			}
		}
		//将有资格的学生放入s[]
		struct Student s[1001];
		int j = 0;
		for(int i = 0; i < n; i++){
			if(stu[i].isEnter != false){
				s[j++] = stu[i];
			}
		} 
		sort(s, s + j, cmp);
		for(int i = 0; i < k; i++){
			if(s[i].isEnter != false)
			cout << s[i].id << " ";
		}
		cout << endl;
	}
	return 0;
}
扫描二维码关注公众号,回复: 12220832 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_43629083/article/details/108893263