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

    解题:

    先排序,再从两头向中间收缩。

    #include <vector>
    #include <iostream>
    #include <algorithm>
    using namespace std;
    class ele{
    public:
    	ele(int a, int b):first(a),second(b){}
    	int first;
    	int second;
    	bool operator < (const ele &m)const{
    		return first < m.first;
    	}
    };
    class Solution {
    public:
        vector<int> twoSum(vector<int> &numbers, int target) {
    		vector<int> result;
    		vector<ele> num_index;
    		int i, j;
    		for(i = 0; i < numbers.size(); i++){
    			ele e = ele(numbers[i], i);
    			num_index.push_back(e);
    		}
    		sort(num_index.begin(), num_index.end());
    		for(i = 0, j = num_index.size() - 1; i < j;){
    			int sum = num_index[i].first + num_index[j].first;
    			if(sum == target){
    				result.push_back(num_index[i].second + 1);
    				result.push_back(num_index[j].second + 1);
    				break;
    			}else if(sum < target){
    				i++;
    			}else if(sum > target){
    				j--;
    			}
    		}
    		sort(result.begin(), result.end());
            return result;
        }
    };
    

      

      

  • 相关阅读:
    linux虚拟机上网
    asp 两种方法连接sql sever 并显示
    了解ado.net 的相关内库--读书笔记
    win10固态硬盘分区方法
    sql sever2012安装错误,无效的十六进制字符
    python学习笔记3
    python 学习笔记4
    python学习笔记2
    20189319《网络攻防》第十周作业
    20189319《网络攻防》第九周作业
  • 原文地址:https://www.cnblogs.com/zhutianpeng/p/4294661.html
Copyright © 2011-2022 走看看