0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

1 解答

Last updated at Posted at 2022-05-14

n^2の解法

 public int[] twoSum(int[] nums, int target) {
		long targetLong = target;
		
		int[] ans = 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] == targetLong) {
					ans[0] = i;
					ans[1] = j;
				}
			}
		}
		return ans;

	}

nの解法

今回のように(同一配列の)二つの要素を組み合わせるにはHashMapがいいのかもしれない。

public int[] twoSum(int[] nums, int target) {
		Map<Integer, Integer> hash = new HashMap<>();
		
		for (int i = 0 ; i < nums.length; i++) {
			int complement = target - nums[i];
			
			if(hash.containsKey(complement)) {
				return new int[] {hash.get(complement), i};
			}
			
			hash.put(nums[i], i);
		}
		throw new IllegalArgumentException();
	}

参考

学んだことを簡単にまとめているだけなので悪しからず。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?