zoukankan      html  css  js  c++  java
  • LeetCode——001 Two Sum

    Description

    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].
    

    ** Solution: **

    可以使用最简单的暴力法

    vector<int> twoSum(vector<int>& nums, int target) {
    	vector<int>v, v1, v2;
    	if (nums.size() <= 0) {
    		return v;
    	}
    	v1 = nums;
    	int num1, num2, p1 = 0, p2 = 0, f = 0;
    	for (int i = 0; i < nums.size(); ++i) {
    		p1 = nums.size() - 1 - i;
    		p2 = p1;
    		num1 = v1.back();
    		v1.pop_back();
    		v2 = v1;
    		for (int j = 0; j < v1.size(); ++j) {
    			num2 = v2.back();
    			p2 = p2 - 1;
    			v2.pop_back();
    			if ((num1 + num2) == target) {
    				v.push_back(p2);
    				v.push_back(p1);
    				f = 1;
    				break;
    			}
    
    		}
    
    		if (f) {
    			break;
    		}
    
    
    	}
    	for (int i = 0; i < v.size(); ++i)
    		v[i]++;
    	return v;
    
    }
    
    
  • 相关阅读:
    mysql免安装使用(win7 64位系统)
    [NOIP2011]瑞士轮
    [NOIP2011]数的划分
    [洛谷2994]超级弹珠
    并查集
    [codevs1073]家族
    快速幂
    [NOI2002]银河英雄传说
    [NOIP2007]矩阵取数游戏
    [洛谷2415]集合求和
  • 原文地址:https://www.cnblogs.com/zzw1024/p/12334038.html
Copyright © 2011-2022 走看看