github demo : https://github.com/happyjiatai/LeetCodeTest/tree/master/1_two_sum
1. search
Use Baidu Search
The first link is leetCode international? The second is the Chinese version. I have entered the Chinese version.
2. interface
3. topic
Just click the sum of the first two numbers
3.1 coding
class Solution { public int[] twoSum(int[] nums, int target) { for(int i = 0; i < nums.length - 1; i++){ for(int j = i + 1; j < nums.length; j++){ if(target == nums[i] + nums[j]){ return new int[]{i, j}; } } } return null; } }
3.2 write test cases
Check the custom test case and write your own input
3.3 execution code
3.4 Android studio test
package com.example.a1_two_sum; public class MyClass { public static void main(String args[]){ Solution solution = new Solution(); int[] result = solution.twoSum(new int[]{12,32,54,1}, 55); if (null == result){ System.out.println("null"); }else{ StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("["); for(int i : result){ stringBuilder.append(i); stringBuilder.append(","); } stringBuilder.deleteCharAt(4); stringBuilder.append("]"); System.out.println(stringBuilder); } } } class Solution{ public int[] twoSum(int[] nums, int target) { for(int i = 0; i < nums.length - 1; i++){ for(int j = i + 1; j < nums.length; j++){ if(target == nums[i] + nums[j]){ return new int[]{i, j}; } } } return null; } }
3.5 submission
3.5.1 official use cases
3.5.2 official answer
In method 2, hashmap is used to eliminate the second level traversal of violent traversal, because the location of hashmap is determined by the hash value, so it is not necessary to traverse in turn. Method 3 is the optimization based on method 2.
4. summary
emmm, one week question?