LeetCodeOJ_001: Two Sum

来源:互联网 发布:值机软件 编辑:程序博客网 时间:2024/06/16 03:37

本文目录

  • 本文目录
  • 题目
  • AC代码

每天一道LeetCode.
原题目:https://leetcode.com/problems/two-sum


题目


Total Accepted: 512743 Total Submissions: 1544952 Difficulty: Easy Contributor: LeetCode

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].
Subscribe to see which companies asked this question.

AC代码

这里写图片描述

import java.util.HashMap;public class Solution {    public int[] twoSum(int[] nums, int target) {        int[] sum = new int[2];        for (int i = 0; i < nums.length; i++) {            for (int j = i+1; j < nums.length; j++) {                if(target - nums[i] == nums[j]) {                    sum[0] = i;                    sum[1] = j;                }            }        }        return sum;    }}
  • Time complexity : O(n^2). For each element, we try to find its complement by looping through the rest of array which takes O(n) time. Therefore, the time complexity is O(n^2).

  • Space complexity : O(1).


这是我的AC代码

public class Solution {    public int[] twoSum(int[] nums, int target) {        int[] result = new int[2];        for(int i=0; i<nums.length; i++) {            //a + b = target            int a = nums[i];            int b = target - a;            for (int j = 0; j < nums.length; j++) {                if ((b == nums[j]) && (i != j)) {                    result[0] = i < j ? i : j;                    result[1] = i > j ? i : j;                    break;                }            }        }        return result;    }}
原创粉丝点击