zoukankan      html  css  js  c++  java
  • leetcode_Two Sum

    Two Sum https://oj.leetcode.com/problems/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


     1 struct Node
     2 {
     3     int num, pos;
     4 };
     5 
     6 bool cmp(Node a, Node b)
     7 {
     8     return a.num < b.num;
     9 }
    10 
    11 class Solution {
    12 public:
    13     vector<int> twoSum(vector<int> &numbers, int target) 
    14     {
    15         vector<int> result;
    16         vector<Node> array;
    17         
    18         for (int i = 0; i < numbers.size(); i++)
    19         {
    20             Node temp;
    21             temp.num = numbers[i];
    22             temp.pos = i;
    23             array.push_back(temp);
    24         }
    25 
    26         sort(array.begin(), array.end(), cmp);
    27         for (int i = 0, j = array.size() - 1; i != j;)
    28         {
    29             int sum = array[i].num + array[j].num;
    30             if (sum == target)
    31             {
    32                 if (array[i].pos < array[j].pos)
    33                 {
    34                     result.push_back(array[i].pos + 1);
    35                     result.push_back(array[j].pos + 1);
    36                 } 
    37                 
    38                 else
    39                 {
    40                     result.push_back(array[j].pos + 1);
    41                     result.push_back(array[i].pos + 1);
    42                 }
    43                 
    44                 break;
    45             } 
    46             
    47             else if (sum < target)
    48             {
    49                 i++;
    50             } 
    51             
    52             else if (sum > target)
    53             {
    54                 j--;
    55             }
    56         }
    57         
    58         return result;
    59     }
    60 };


  • 相关阅读:
    lucene学习-创建索引
    ExtJs学习-搭建开发环境
    Struts2上传文件(1)
    使用USBWriter做U盘启动盘后U盘在盘中不显示的解决办法(轉載)
    家里旧电脑装了centos7實踐思路
    win7/win10下装centos7双系统(转载)
    美区google play礼品卡,如何正确充值到美区google play余额,并能购买游戏道具
    excel 2016 打开UTF-8编码CSV文件乱码的问题UTF-8编码CSV文件乱码的问题
    python3 writerow CSV文件多一个空行
    python3 UnicodeEncodeError: 'gbk' codec can't encode character 'xa0' in position 4400: illegal multibyte sequence
  • 原文地址:https://www.cnblogs.com/zss/p/3854944.html
Copyright © 2011-2022 走看看