fireholder.github.io

伪文艺女青年,状高冷,话少爱热闹


Blog | Archive | About

LeetCode 1 : Array:Two Sum

03 Nov 2016 | LeetCode

自去年开始学C以来,也算是接触了许多编程语言,虽说也算是几乎每天都在敲代码,惭愧的是只学了皮毛语法,也要忘个精光,算法更是一窍不通的。这几天翻出以前想刷的编程题,趁着写博客,打算一鼓作气把LeetCode刷完,好好整理一下思路。

由于我接触的有的语言差异很大,其中有的题目可能会用多种语言解答。

注:此处代码均已AC过。

Problem

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


Explanation 1

这是第一题,比较简单,根据题意只存在唯一解,大大降低了难度。 此处我用两个游标遍历整个数组,若找到相加为目标数的两个游标, 且两个游标不重复的话,则返回值为这两个游标的数组,并且将较小的放在前面。

Solution for Java

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] index=new int[2];
	for(int i=0;i<nums.length;i++){
		for(int j=0;j<nums.length;j++){
			if((nums[i]+nums[j]==target) && i<j){
				index[0]=i;
			    	index[1]=j;
			}
		}
	}
	return index;
    }
}


Explanation 2

此处遍历整个list,如果找到目标数减去遍历值仍为所给list中的值,则返回它们的 游标。

Solution for Python

class Solution(object):
    def twoSum(self, nums, target):
        ""
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        ""
        index=[]
	    	for i,num in enumerate(nums):
	    		if target-num in nums:
	    			for j in range(len(nums)):
	    				if nums[j]==target-num and i<j:
	    					index.insert(0,i)
	    					index.insert(1,j)
	    					return index
    					
		
comments powered by Disqus

Older · View Archive (56)

硬件学习之电机

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

电机的选择

Newer

LeetCode 2 : Add Two Numbers

Problem

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.