排序很重要

算法与数据结构中,有时候需要先排序在做其他事情,这里总结一些比较有趣的题目,说明排序在解题过程中的重要性。

242. Valid Anagram [LeetCode]
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;
// 类似于华为的兄弟单词那个题
bool isAnagram(string s, string t) {

    sort(s.begin(), s.end());
    sort(t.begin(), t.end());

    return s == t;
}
查找兄弟单词

题目说明请看华为机试题查找兄弟单词

#include<iostream> 
#include<string> 
#include<vector> 
#include<algorithm> 

using namespace std;

// 这里,不能传引用
bool isBrother(string a, string b){

    sort(a.begin(), a.end());
    sort(b.begin(), b.end());

    if (a == b)return true;

    return false;
}

void showBrother(const vector<string>& v){
    cout << "------------ Brother words --------------" << endl;
    for (auto str : v){
        cout << str << endl;
    }
}

int test(){

    int n;

    vector<string> word_dict;
    vector<string> brother_word;

    while (cin >> n){

        word_dict.clear();
        brother_word.clear();

        string temp;
        for (int i = 0; i < n; i++)
        {
            cin >> temp;
            word_dict.push_back(temp);
        }

        string key_word;
        int index;

        cin >> key_word;
        cin >> index;

        // 查找是不是兄弟单词
        for (int i = 0; i < word_dict.size(); i++)
        if (key_word != word_dict[i] && isBrother(key_word, word_dict[i]))
            brother_word.push_back(word_dict[i]);

        sort(brother_word.begin(), brother_word.end());
        cout << brother_word.size() << endl;

        if (index <= brother_word.size())
            cout << brother_word[index - 1] << endl;

        showBrother(brother_word);
    }
    return EXIT_SUCCESS;
}
改试卷(美团点评)

请查看前面的博客,2017美团机试题目改试卷(美团点评)

排序+对撞指针

请查看前面的博客,LeetCode经典问题3 SUM

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值