leetcode - 1


Java学习者论坛:www.javaxxz.com

1. 题目

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


2. 代码实现

import java.util.Arrays;
import java.util.HashMap;
/**
* @author: UniqueZ_
* @file: the first question of leetcode - two sum
* @date: 2017-06-22
*/

public class TwoSum {

private int[] arr;
private int target;

public TwoSum(int[] arr, int target) {
this.arr = arr;
this.target = target;
}

// force method - O(n^2)
public int[] twoSum_force() {
int arrLength = arr.length;
for (int i = 0; i < arrLength; i++) {
for (int j = i; j < arrLength; j++) {
if (arr[i] + arr[j] == target) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No solution founded.");
}

// hash method - O(n)
public int[] twoSum_hash() {
HashMap<Integer, Integer> hMap = new HashMap<>();
int arrLength = arr.length;
for (int i = 0; i < arrLength; i++) {
if (hMap.containsKey(target - arr[i])) {
return new int[] { hMap.get(target - arr[i]), i };
}
hMap.put(arr[i], i);
}
throw new IllegalArgumentException("No solution founded.");
}

// main - test the two methods
public static void main(String[] args) {
int[] arr = new int[] { 1, 2, 3, 4 };
int target = 4;
int[] result = new int[2];
TwoSum object = new TwoSum(arr, target);

result = object.twoSum_hash();
System.out.println(Arrays.toString(result));
}
}


本站声明
本文转载自:http://blog.csdn.net/zk_j1994/article/details/73729678     作者:ZK_J1994     发布日期:2017/06/25     本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。


 
© 2014-2017 ITdaan.com 粤ICP备14056181号