1. import java.util.Arrays;
    2. /**
    3. * 给定一个整数数组 nums和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那两个整数,并返回它们的数组下标。
    4. * 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
    5. * 你可以按任意顺序返回答案。
    6. *
    7. *
    8. * 示例 1:
    9. *
    10. * 输入:nums = [2,7,11,15], target = 9
    11. * 输出:[0,1]
    12. * 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
    13. * 示例 2:
    14. *
    15. * 输入:nums = [3,2,4], target = 6
    16. * 输出:[1,2]
    17. * 示例 3:
    18. *
    19. * 输入:nums = [3,3], target = 6
    20. * 输出:[0,1]
    21. *
    22. * 来源:力扣(LeetCode)
    23. * 链接:https://leetcode-cn.com/problems/two-sum
    24. */
    25. public class TwoNumSum {
    26. public static int[] solve(int[] num,int target){
    27. int[] result = new int[2];
    28. for(int i = 0;i<num.length;i++){
    29. for(int j = 0 ;j<num.length;j++){
    30. if(i!=j){
    31. if(num[i]+num[j] == target){
    32. result[0] = i;
    33. result[1] = j;
    34. }
    35. }
    36. }
    37. }
    38. return result;
    39. }
    40. //先排序,排序完成在数组里面查找对应的下标,使用二分查找,找到了再去检索原数组 o(nlogn)+o(nlogn)+n ->o(nlogn)
    41. public static int[] solve2(int[] num,int target){
    42. int[] result = new int[2];
    43. int copy[] = new int[num.length];
    44. System.arraycopy(num,0,copy,0,num.length);
    45. Arrays.sort(copy);
    46. int x =0,y =0;
    47. boolean find =false;
    48. for(int i =0;i<copy.length-1;i++) {
    49. if(copy[i]*2 <= target) {
    50. int index = Arrays.binarySearch(copy, i+1 , copy.length, target - copy[i]);
    51. if (index > 0) {
    52. find = true;
    53. x = copy[i];
    54. y = copy[index];
    55. }
    56. }
    57. }
    58. if(find){
    59. for (int i =0;i<num.length;i++) {
    60. if(num[i] == x){
    61. result[0] = i;
    62. }else if(num[i] == y){
    63. result[1] = i;
    64. }
    65. }
    66. }
    67. return result;
    68. }
    69. //Hash表查找 O(n),预处理将数组中的数据放到HashMap中,再去找
    70. public static int[] solve3(int[] num,int target){
    71. int[] result = new int[2];
    72. Map<Integer,Integer> indexMap = new HashMap<>();
    73. for (int i = 0; i < num.length; i++) {
    74. indexMap.put(num[i],i);
    75. }
    76. for(int i=0;i<num.length;i++){
    77. int y = target - num[i];
    78. if(indexMap.get(y) !=null){
    79. result[0] = i;
    80. result[1] = indexMap.get(y);
    81. }
    82. }
    83. return result;
    84. }
    85. public static void main(String[] args) {
    86. int[] num = {2,7,11,15};
    87. int target = 9;
    88. int[] result =TwoNumSum.solve2(num,target);
    89. for(int i =0;i< result.length;i++){
    90. System.out.println(result[i]);
    91. }
    92. }
    93. }