• Two Sum


    题目链接

    Two Sum - LeetCode

    注意点

    • 这题似乎结果排序不重要,也就是说[0,1]和[1,0]是一样的

    解法

    解法一:看到题目第一反应就是遍历数组,时间复杂度为O(n^2)。抱着试一试的心态打了一下,居然过了。

    int* twoSum(int* nums, int numsSize, int target) {
        int* anw = (int *) malloc(2 * sizeof(int));
        int i,j;
        for(i = 0;i < numsSize;i++)
        {
            for(j = i+1;j < numsSize;j++)
            {
                if(nums[i] + nums[j] == target)
                {
                    anw[0] = i;
                    anw[1] = j;
                }
            }
        }
        return anw;
    }
    

    解法二:用map保存每个数字出现的位置,时间复杂度为O(n)

    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            map<int,int> myMap;
            vector<int> anw;
            for(int i = 0;i < nums.size();i++)
            {
                if(myMap.count(target - nums[i]))
                {
                    anw.push_back(i);
                    anw.push_back(myMap[target - nums[i]]);
                }
                myMap[nums[i]] = i;
            }
            return anw; 
        }
    };
    

    解法三:数组快速排序,维护两个指针,一个指向头部一个指向尾部,如果头部加尾部的值小于target,头部指针向后移动;如果大于target,尾部指针向前移动。排序过程中注意保存数字新下标和原来下标的对应关系。时间复杂度O(nlogn),并没有优于解法二我就不打了 (其实是我忘了快排怎么打)

    小结

    • 太久没打代码了,这么简单的题目都要想半天...
    • STL容器的使用忘光了,是不能用这种方式赋值的,还查了半天错( ╯□╰ )
    vector<int> anw;
    anw[0] = 1;
    
  • 相关阅读:
    MapReduce案例WordCount
    MapReduce排序案例
    MapReduce倒排索引
    MapReduce自定义排序编程
    GroupingComparator 自定义分组
    CombineTextInputFormat小文件处理场景
    cdh 2.6.0版本和apache 2.7.x版本 本地执行环境的差异。
    DistributedCache 分布式缓存
    MapReduce数据压缩机制
    MapReduce其他功能
  • 原文地址:https://www.cnblogs.com/multhree/p/10290272.html
Copyright © 2020-2023  润新知