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

    Given an array of integers, find two numbers such that they add up to a specific target number.

    The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

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

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2

    新建一个数组,分别保存原数组的值和索引,并对新数组按值排序,之后按照2Sum的方法,左右两根指针就可以找解了。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 };
  • 相关阅读:
    企业信息开发平台(5)流程设计(一)
    企业信息开发平台(6)Web表单设计器开源
    Guava的常用方法示例
    apk反编译
    公司注册登记流程
    Git 使用流程
    ZIP压缩和解压字符串
    vue+elementui实现无限级动态菜单树
    vue 开发笔记
    从零到一开发博客后台管理系统(一)
  • 原文地址:https://www.cnblogs.com/chkkch/p/2772251.html
Copyright © 2011-2022 走看看