LeetCode刷题(Java)——1. Two Sum

Question:

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

英文看不懂的娃不用担心,看例子就能懂。上本娃子的代码:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int i,j;
        int[] result = new int[2];
        for(i=0;i

本娃子严格按照前辈的要求开始刷题,自己思考,不用IDE工具,你会发现没有提示写代码就成码盲了,这样练习一下挺好的,然后左下角 Custom Testcase可以输入测试案例,点击右下角Run Code,就能在下方看到自己代码的输出结果了,不用额外写main方法,它会给你很多提示,你一条条修改。本娃子列出几个重要的点如下:

1.当我把return 放到if语句里面的时候提示“missing return statement”,然后我就明白了。

2.for循环那里需要注意,j从i+1开始,因为这里的数据不能重复使用。

第一次提交后就AC啦,虽然题目简单,但是开门红啊,好开心啊。然后翻看一下前辈的代码,我去!还能这样写啊,666,贴上代码(看完思路自己码出来的,不是直接复制的)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map map= new HashMap();
        int[] result = new int[2];
        for(int i=0;i

 

最后再去CleanCodeHandbook_v1.0.3里看一下复杂度的解析,主要是降低了时间复杂度,受益匪浅,新方法能够节约: 

 

   我的运行时间(37ms)-改进后的(4 ms)=33!

真切的感受到智商的魅力。

思考:如果给定的数组已经按照升序排序怎么办? 

 

 

 

你可能感兴趣的:(LeetCode)