zoukankan      html  css  js  c++  java
  • 1. Two Sum

    Total Accepted: 238787 Total Submissions: 999694 Difficulty: Easy

    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.

    Example:

    Given nums = [2, 7, 11, 15], target = 9,
    
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].
    

    UPDATE (2016/2/13):
    The return format had been changed to zero-based indices. Please read the above updated description carefully.

    Subscribe to see which companies asked this question

     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int>& nums, int target) {
     4         vector<int> v = nums;
     5         vector<int> w;
     6         sort(nums.begin(), nums.end());
     7         int i = 0, j = nums.size() - 1;
     8         while (i < j){
     9             if (nums[i] + nums[j] == target){
    10                 for (int m = 0; m < v.size(); m++){
    11                     if (v[m] == nums[i]){
    12                         w.push_back(m);
    13                         continue;
    14                     }
    15                     if (v[m] == nums[j]){
    16                         w.push_back(m);
    17                     }
    18                 }
    19                 sort(w.begin(), w.end());
    20                 break;
    21             }
    22             else if (nums[i] + nums[j] < target){
    23                 i++;
    24             }
    25             else{
    26                 j--;
    27             }
    28         }
    29         return w;
    30     }
    31 };
     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int>& nums, int target) {
     4         vector<int> v;
     5         map<int, int> m;
     6         map<int, int>::iterator iter;
     7         for (int i = 0; i < nums.size(); i++){
     8             int complement = target - nums[i];
     9             iter = m.find(complement);
    10             if(iter != m.end())
    11             {
    12                 v.push_back(m[complement]);
    13                 v.push_back(i);
    14                 break;
    15             }
    16             m[nums[i]] = i;
    17         }
    18         return v;
    19     }
    20 };
  • 相关阅读:
    洛谷 P1084 疫情控制 —— 二分+码力
    CF 600 E Lomsat gelral —— 树上启发式合并
    HBase框架基础(二)
    Shell脚本
    Kafka框架基础
    HUE搭配基础
    Oozie框架基础
    Sqoop框架基础
    Flume框架基础
    Hive框架基础(二)
  • 原文地址:https://www.cnblogs.com/wanderingzj/p/5554337.html
Copyright © 2011-2022 走看看