LeetCode之1.Two Sum

问题描述

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

问题思考

—–看到这个问题,我们首先做的应该是思考如何解决,在脑海中给一个思维导图,我想的是这个应该是像冒泡排序一样,写两个嵌套的for循环,然后换一下if判断即可。

# 冒泡排序# 定义列表 list
arays = [1,8,2,6,3,9,4]
for i in range(len(arays)):
    for j in range(i+1):
        if arays[i] < arays[j]:
            # 实现连个变量的互换
            arays[i],arays[j] = arays[j],arays[i]
print arays

—–上面这个是Python菜鸟教程上的冒泡排序的程序例子,个人感觉这个例子很好,首先第一个是这个range(i+1)很巧妙,为此我专门上网查了下资料,range(start, stop[, step]),如果start缺省,则默认start为0,如果step缺省,则默认为1,这个与我们学过的其他语言类似,还有就是range(start,stop)是一个左闭右开的虚列数。下面是几个例子

>>> range(5)
[0, 1, 2, 3, 4]
>>> range(1,5)
[1, 2, 3, 4]
>>> range(1,5,2)
[1, 3]

—–看了这个range函数的介绍,我还是觉得上面的那个range(i+1)很难理解,经过思前想后,我发现range(i+1)是为了排除range(0)=[],这个特殊情况。排序在之前所学的C语言中:

//冒泡排序
void sort(int *a,int len)
{
    int i=0;
    int j;
    int t;
    for(i=0;i<len-1;i++)[1] 
    {
        for(j=0;j<len-i-1;j++)//for(j=1;j<len-i;j++)
        {
            if(a[j]>a[j+1])
                {
                    t=a[j];
                    a[j]=a[j+1];
                    a[j+1]=t;
                }
        }
    }
}
//选择排序 
void sort(int *p,int len)
{
    int i,j;
    for(i = 0;i<len;i++)
    {
        for(j = i+1;j<len;j++)
        {
            if(p[i]>p[j])
            {
                int tmp = p[i];
                p[i] = p[j];
                p[j] = tmp;
            }
        }
    }
}

我的解决方法 —Python

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        rlist=[]
        for indice1 in range(len(nums)):
            for indice2 in range(indice1+1,len(nums)-1):
                if nums[indice1]+nums[indice2]==target:
                    rlist.append(indice1)
                    rlist.append(indice2)
                    return rlist
Your input
[3,2,4]
6
Your answer
[1,2]
Expected answer
[1,2]

—–事实证明,上面的Python代码中,第二层循环不能使用之前所猜想的哪样,用range(i+1),因为这样会得到结果[0,0],也就是这样的话,会存在一个数被用两次的情况。

我的解决方法 —C

#include<stdio.h>
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target) {
    int *a = (int*)malloc(2*sizeof(int));  
    for(int i=0;i<numsSize;i++)
    {
        for(int j=i+1;j<numsSize;j++)//j=i+1在这里等价表达于j!=i
        {
            if(nums[i]+nums[j]==target)
            {
               a[0]=i;
               a[1]=j;
            }
        }    
    }
    return a;
}
int main(void) {
    int *a = (int*)malloc(2*sizeof(int)); 
    //int *nums=(int*)malloc(4*sizeof(int));//动态数组(int *)malloc(sizeof(int)*n)
    int *nums[4]={2,7,11,15};//只有在数组声明的时候才可以这样赋值
    int target = 9;
    int numsize=4;
    a=twoSum(nums,numsize,target);
    return 0;
}

—–注意C语言上,我们申请数组空间的代码,以及数组赋值使用a=[2,7,11,15]是错误的,C语言赋值方法只有以下两种情况:

1、初始化时进行赋值。
int a[2] = {1,2};
char str[20] = "hello world";
2、逐个赋值
int a[4];
a[0] = 1,a[1]=2, a[2] = 3, a[4]=4;
-----C语言的解决方法中,我们还需要注意的是括号的问题,for循环(多行代码块)和if语句(多行代码块)都必须使用{},不然的话,很容易出现值的,问题。

我的解决方法 —Java

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

    public static void main(String[] args)
    {

        int[] test= {2,7,11,15};
        for (int i : test) 
        {
            System.out.print(i+" ");
        }
        System.out.println("\n");
        int target=9;
        int[] a=new int[2];
        a=twoSum(test,target);
        for (int i : a) 
        {
            System.out.print(i+" ");
        }

    }
}
//结果
Finished in 112 ms
2 7 11 15 
0 1 

我的解决方法 —Swift

class Solution {
    func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
        var a = [Int]()  //var a:[Int] = [10, 20, 30]
        for i in 0..<nums.count {
            for j in i+1..<nums.count {
                if target == nums[i] + nums[j] {
                    a = [i, j]
                    return a
                }
            }
        }
        return a
    }
}

—–Swift语言给我最深的印象就是简介,例如数组赋值,直接a=[i,j],这样直接把i,j的值传给了数组a,哇,这个秒杀C,java,由于自己一直想去Apple工作,所以就想每天花点时间学习下Swift,让自己离目标更近一点,即使以后不能去Apple工作,也希望以后会偶尔在App Store开发一些自己喜欢的小应用。

—–最后送给像我一样零点起步的菜鸟们,只要你自己肯努力,无论别人怎么说,什么时候都不算晚。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值