zoukankan      html  css  js  c++  java
  • Q4: 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

    解决原理:

    数组以升序排序

    从数组S头、尾同时遍历数组,i为头端索引,j为尾端索引

    若S[i]+S[j]=target,则返回对应索引

    若S[i]+S[j]>target,则j--

    否则i++

    代码:

     

     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int> &numbers, int target) {
     4         int i = 0;
     5         int j = numbers.size()-1;
     6         int sum;
     7         vector<int> rs;
     8         vector<int> tmp;
     9         
    10         for(int k = 0; k < numbers.size(); k++) 
    11             tmp.push_back(numbers[k]);
    12             
    13         sort(tmp.begin(), tmp.end());
    14         while(i < j){
    15             sum = tmp[i] + tmp[j];
    16             if(sum == target){
    17                 int m = 0;
    18                 while(numbers[m] != tmp[i]) m++;
    19                 int n = 0;
    20                 while(numbers[n] != tmp[j]) n++;
    21                 if(n == m){
    22                     n++;
    23                     while(numbers[n] != tmp[j]) n++;
    24                 }
    25                 
    26                 rs.push_back(m>n?n+1:m+1);
    27                 rs.push_back(m>n?m+1:n+1);
    28                 return rs;
    29             }else if(sum < target){
    30                 i++;
    31             }else{
    32                 j--;
    33             }
    34         }
    35         return rs;
    36     }
    37 };
  • 相关阅读:
    (1)李宏毅深度学习-----机器学习简介
    Git命令之不得不知的git stash暂存命令
    Http2升级方案调研
    神奇的 SQL 之别样的写法 → 行行比较
    熔断机制
    限流算法
    状态机
    布隆过滤器
    负载均衡算法
    K8S Ingress
  • 原文地址:https://www.cnblogs.com/ISeeIC/p/4355803.html
Copyright © 2011-2022 走看看