Leet Code OJ 1. Two Sum [Difficulty: Easy]

本文解析了一道经典算法题“两数之和”,提供了两种Java实现方案,并分享了作者学习算法的心得体会,强调了算法在实际工作中的重要性和实用性。

题目: 
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].

Java版代码1(时间复杂度O(n)):

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map=new HashMap<>();
        for(int i=0;i<nums.length;i++){
            Integer index=map.get(target-nums[i]);
            if(index==null){
                map.put(nums[i],i);
            }else{
                return new int[]{i,index};
            }
        }
        return new int[]{0,0};
    }
}
Java版代码2(时间复杂度O(n^2)):

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


算法!

      学了算法到底有没有用?

  以前我觉得没什么用,工作很长一段时间都没有用上。后来刷了LeetCode,在老大交给我的几个任务里都用到了一些,例如这一章译文中提到的哈希表,直接把某个数据筛选环节的运行时间从原来的半个小时缩短到10秒,速度足足提升了将近两百倍。

  算法并不是没有用,而是如果一个程序员不懂算法,在实际的编程中他就想不到用哪个算法比较好,只会一味用暴力算法或者是API自带的函数。我惊喜地发现,如果你开始懂一点算法,知道在什么情景下适用,将会带来超乎想象的好处。另一方面,也不要把算法想得那么高深和艰涩,大部分实用的算法都只是20行左右的代码就能实现。

   只要你能鼓起勇气,克服因为未知而产生的恐惧,花一点时间和耐心去学习,将会看到一个完全不一样的世界。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值