Two Sum
题目描述:
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].
解决代码:
package com.jack.algorithm;
import com.alibaba.fastjson.JSONObject;
/**
* create by jack 2018/8/8
*
* @auther jack
* @date: 2018/8/8 22:25
* @Description:
* 两数之和
*/
public class SumTwoNum {
//题目描述:https://leetcode-cn.com/problems/two-sum/description/
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");
}
public static void main(String[] args) {
SumTwoNum twoNum = new SumTwoNum();
System.out.println(JSONObject.toJSONString(twoNum.twoSum(new int[]{2, 7, 11, 15},9)));
}
}
代码地址:
https://github.com/wj903829182/LeetCodeStudy/blob/master/src/main/java/com/jack/algorithm/AddTwoNum.java
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。