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

    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, and you may not use the same element twice.

    Example:

    Given nums = [2, 7, 11, 15], target = 9,
    
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].
     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int>& nums, int target) {
     4         vector<int> num=nums;
     5         sort(num.begin(), num.end());
     6         int len = num.size();
     7         int left = 0;
     8         int right = len - 1;
     9         while (left < right)
    10         {
    11             if ((num[left] + num[right])>target)
    12                 right--;
    13             else
    14             if ((num[left] + num[right]) < target)
    15                 left++;
    16             else
    17                 break;
    18         }
    19         vector<int> vet;
    20         for(int i=0;i<len;i++)
    21         {
    22             if(nums[i]==num[left]||nums[i]==num[right])
    23                vet.push_back(i);
    24         }
    25        
    26         return vet;
    27     }
    28 };
  • 相关阅读:
    zoj-1610线段树刷题
    poj-3268最短路
    poj-2528线段树练习
    线段树-最小逆序数hdu1394
    线段树延迟更新
    hdu-4027线段树练习
    RMQ_第一弹_Sparse Table
    字符串hash与字典树
    背包问题
    网络流
  • 原文地址:https://www.cnblogs.com/wujufengyun/p/7115029.html
Copyright © 2011-2022 走看看