Leetcode una pregunta por mes: la suma de dos números

Leetcode una pregunta por mes

Suma de dos números

Dado un número de matriz de enteros y un objetivo de valor objetivo, busque los dos enteros cuya suma sea el valor objetivo en la matriz y devuelva sus subíndices de matriz.

Puede asumir que cada entrada solo corresponderá a una respuesta. Sin embargo, el mismo elemento de la matriz no se puede utilizar dos veces.

Ejemplo:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
		所以返回 [0, 1]
responder:
class Solution {
    
    
    public int[] twoSum(int[] nums, int target) {
    
    
        int[] result = new int[2];
        for(int i = 0; i < nums.length; i++){
    
    
            for(int j = i+1; j < nums.length; j++){
    
    
                if(nums[i] + nums[j] == target){
    
    
                    result[0] = i;
                    result[1] = j;
                    break;
                }
            }
        }
        return result;
    }
}

Otras respuestas: método de tabla hash, espacio para el tiempo.

class Solution {
    
    
    public int[] twoSum(int[] nums, int target) {
    
    
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
    
    
            int complement = target - nums[i];
            if (map.containsKey(complement)) {
    
    
                return new int[] {
    
     map.get(complement), i };
            }
            //先插入会导致同一元素使用两次
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

Supongo que te gusta

Origin blog.csdn.net/ZMXQQ233/article/details/107617524
Recomendado
Clasificación