2sum

来源:互联网 发布:软件开发工作量报价 编辑:程序博客网 时间:2024/05/29 16:43
class Solution {    public int[] twoSum(int[] nums, int target)    {        int [] ans = 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)                {                    ans[0] = i;                    ans[1] = j;                }            }        }        return ans;    }}

第一次写博客leetcode第一题 twosum,这是我实现的代码,时间复杂度O(n方)。效率比较低

这是网上找的代码 实现效果好一点

class Solution {    public int[] twoSum(int[] nums, int target) {        for(int i=0;i<nums.length;i++){            for(int j=i+1;j<nums.length;j++){                if(nums[j]==target-nums[i]){                    return new int[]{i,j};                }    }}        throw new IllegalArgumentException("No two sum solution");}}

原创粉丝点击