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

    class Solution {
    public:
        vector<int> twoSum(vector<int> &numbers, int target) {
             vector<int> result;
            result.resize(2);
            multimap<int,int> nummap;
            int i = 1;
            vector<int>::iterator begin = numbers.begin(),p = begin;
            for(;p != numbers.end();p++)
            {
                nummap.insert(pair<int,int>(*p,i));
                i++;
            }
    
            multimap<int,int>::iterator index_fir = nummap.begin(),index_sec = nummap.end();
            index_sec--;
            while(index_fir != index_sec)
            {
                if(((*index_fir).first + (*index_sec).first) == target)
                {
                    if((*index_fir).second > (*index_sec).second)
                    {
                        result[0] = (*index_sec).second;
                        result[1] = (*index_fir).second;
                        return result;
                    }else
                    {
                        result[1] = (*index_sec).second;
                        result[0] = (*index_fir).second;
                        return result;
                    }
                }else if(((*index_fir).first + (*index_sec).first) < target)
                {
                    index_fir++;
                }else
                {
                    index_sec--;
                }
            }
            return result;
        }
    };


    能力较水,写的不咋滴
  • 相关阅读:
    4:4 自定义拦截器
    DDD学习笔记一
    Winform/WPF国际化处理
    NPOI 操作Excel
    将输入的字符串进行大写格式化
    将输入的字符串分2个字符添加空格并大写格式化
    VS使用技巧
    NotifyIcon用法
    C#Winfrom系统打印机调用/设置默认打印机
    TextBox(只允许输入字母或者数字)——重写控件
  • 原文地址:https://www.cnblogs.com/wangtengxiang/p/4200886.html
Copyright © 2011-2022 走看看