zoukankan      html  css  js  c++  java
  • [Leetcode] Two Sum

    1. Sort : O(n*lgn)

    2. two points search from both ends to middle : O(n)

     1 struct Node
     2  {
     3      int val;
     4      int index;
     5      Node(){}
     6      Node(int v, int idx):val(v), index(idx){}
     7  };
     8  
     9  bool compare(const Node &lhs, const Node &rhs)
    10  {
    11      return lhs.val < rhs.val;
    12  }
    13  
    14  class Solution {
    15  public:
    16      vector<int> twoSum(vector<int> &numbers, int target) {
    17          // Start typing your C/C++ solution below
    18          // DO NOT write int main() function
    19          vector<Node> a;
    20          for(int i = 0; i < numbers.size(); i++)
    21              a.push_back(Node(numbers[i], i + 1));
    22          sort(a.begin(), a.end(), compare);
    23          
    24          int i = 0;
    25          int j = numbers.size() - 1;
    26          while(i < j)
    27          {
    28              int sum = a[i].val + a[j].val;
    29              if (sum == target)
    30              {
    31                  vector<int> ret;
    32                  int minIndex = min(a[i].index, a[j].index);
    33                  int maxIndex = max(a[i].index, a[j].index);
    34                  ret.push_back(minIndex);
    35                  ret.push_back(maxIndex);
    36                  return ret;
    37              }
    38              else if (sum < target)
    39                  i++;
    40              else
    41                  j--;
    42          }
    43      }
    44  };
  • 相关阅读:
    uboot编译配置过程
    APUE-数据库函数库
    值得推荐的C/C++框架和库 (真的很强大)
    ubuntu12.04图形界面与命令行界面切换
    ubuntu14.04 升级gcc的方法
    4. H5+css3
    3,css 内容
    2. 浏览器兼容性问题
    1,http协议
    页面添加水印
  • 原文地址:https://www.cnblogs.com/longdouhzt/p/2940223.html
Copyright © 2011-2022 走看看