• LeetCode1 Two Sum


    题目 :Given an array of integers, return indices of the two numbers such that they add up to a specific target.

    You may assume that each input would have exactly one solution.  (Easy)

    解法1: Two pointers

    拷贝一份,将数组排序,两根指针分别从前后向中间扫描,找到解为止。再遍历原数组寻找下标添加到结果内。

    复杂度: O(nlogn)

    注意:比如0,3,4,0  target = 0这组数据,需要让result第二个参数从后向前扫描才能保证答案正确。

    代码:

     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int>& nums, int target) {
     4         vector<int> v(nums);
     5         vector<int> result;
     6         sort(nums.begin(), nums.end());
     7         int i = 0,j = nums.size() - 1;
     8         while (nums[i] + nums[j] != target) {
     9             if (nums[i] + nums[j] > target) {
    10                 j--;
    11             }
    12             else {
    13                 i++;
    14             }
    15         }
    16         for (int k = 0; k < nums.size(); ++k) {
    17             if (v[k] == nums[i]) {
    18                 result.push_back(k);
    19                 break;
    20             }
    21         }
    22         for (int k = nums.size() - 1; k >=  0; --k) { //从后向前扫描
    23            if (v[k] == nums[j]) {
    24                 result.push_back(k);
    25                 break;
    26             }
    27         }
    28         return result;
    29     }
    30 };

    解法2:

    利用hash表建立数值与下标的一一对应,扫描一遍即得解。

    注: 本以为是O(n),但运行时间比解法1居然慢,查看discuss得知没有注意find()方法在最差情况下执行效率是O(n)的。

    代码:

     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int>& nums, int target) {
     4         //数值 与 下标一一对应
     5         unordered_map<int,int> hash;
     6         vector<int> result;
     7         for (int i = 0; i < nums.size(); ++i){
     8             if (hash.find(target - nums[i]) != hash.end()) {
     9                 result.push_back(hash[target - nums[i]]);
    10                 result.push_back(i);
    11                 return result;
    12             }
    13             hash[nums[i]] = i;
    14         }
    15         return result;
    16     }
    17 };
  • 相关阅读:
    洛谷P2345 奶牛集会
    洛谷P3531 [POI2012]LIT-Letters
    codevs 4163 hzwer与逆序对
    各种读入方式速度比较
    洛谷P1420 最长连号
    TCPDump:捕获并记录特定协议 / 端口
    linux下抓取网页快照
    Pro Android 4 第五章 理解Intent
    UpdatePanel和jQuery不兼容
    RAC 11.2.0.4 安装 遇到 INS-06001
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5723667.html
Copyright © 2020-2023  润新知