[Leetcode series] Two sum

Source: Internet
Author: User

Solution 1: what I think is a little weak, time complexity O (N ^ 2 ).

public class Solution {public int[] twoSum(int[] numbers, int target) {int[] result = new int[2];for (int i = 0; i < numbers.length; i++) {for (int j = i + 1; j < numbers.length; j++) {if (numbers[i] + numbers[j] == target) {result[0] = i;result[1] = j;}}}if (result[0] == 0) {if (result[1] != 1) {int tmp = numbers[0];numbers[0] = numbers[1];numbers[1] = tmp;result[0] = 1;} else {int tmp = numbers[1];numbers[1] = numbers[2];numbers[2] = tmp;result[1] = 2;tmp = numbers[0];numbers[0] = numbers[1];numbers[1] = tmp;result[0] = 1;}}return result;}public void arrayPrint(int[] array) {for (int i = 0; i < array.length; i++) {System.out.print(array[i] + " ");}System.out.println();}public static void main(String[] args) {int[] numbers = { 11, -22, 12, 7, 2 };int target = 9;Solution mSolution = new Solution();mSolution.arrayPrint(numbers);int[] result = mSolution.twoSum(numbers, target);mSolution.arrayPrint(result);mSolution.arrayPrint(numbers);}}

Solution 2: Click to open the link on the Internet. It is clever to use Java hashtable to change the typical space for time and time complexity O (N), but it must meet the requirements of the following standards, after finding the numbers that meet the conditions, you must sort them again. The following code is slightly modified:

public int[] twoSum_2(int[] numbers, int target) {int[] result = new int[2];HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();for(int i = 0; i < numbers.length; i++) {if(hm.get(target - numbers[i]) != null) {result[0] = hm.get(target - numbers[i]);result[1] = i;} else {hm.put(numbers[i], i);}}if (result[0] == 0) {if (result[1] != 1) {int tmp = numbers[0];numbers[0] = numbers[1];numbers[1] = tmp;result[0] = 1;} else {int tmp = numbers[1];numbers[1] = numbers[2];numbers[2] = tmp;result[1] = 2;tmp = numbers[0];numbers[0] = numbers[1];numbers[1] = tmp;result[0] = 1;}}return result;}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.