Leetcode(Hash)

发布时间 2023-09-13 16:23:04作者: PostMan_Zc

1.the sum of two nums

1.1Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

1.2You may assume that each input would have exactly one solution, and you may not use the same element twice.

1.3You can return the answer in any order.

Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?

method1:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result=new int[2];//the result data
        for(int i=0;i<nums.length;i++){  
            for(int j=i;j<nums.length;j++){
                if(nums[i]+nums[j]==target){
                    if(i!=j){  //judging if the index is the same
                        result[0]=i;
                        result[1]=j;
                    }
                }
            }
        }
        return result;
    }
}