Skip to main content

TWO SUM -LEET CODE PROBLEM 1

  https://leetcode.com/problems/two-sum/

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

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

You can return the answer in any order.

 

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

class Solution {

    public int[] twoSum(int[] nums, int target) {

    

        HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();

        

        for(int i=0;i<nums.length;i++){

            

            if(map.get(nums[i])==null){

                map.put(target-nums[i],i);

            }

            else{

                return new int[]{map.get(nums[i]),i};

            }

        }

        return null;

    }

}


Comments

.

Popular posts from this blog

BREADTH FIRST SEARCH IN JAVA

BREADTH FIRST SEARCH IN JAVA:- package com . problems . graph ; import java.awt.DisplayMode ; import java.util.Iterator ; import java.util.LinkedList ; public class BFSGraph { int maxsize ; Vertex vertexlist []; int matrixlist [][]; int vertexcount ; @SuppressWarnings ({ "rawtypes" , "unused" }) LinkedList queue ; public BFSGraph () { maxsize = 20 ; matrixlist = new int [ maxsize ][ maxsize ]; vertexlist = new Vertex [ maxsize ]; for ( int i = 0 ; i < maxsize ; i ++) { for ( int j = 0 ; j < maxsize ; j ++) { matrixlist [ i ][ j ]= 0 ; } } queue = new LinkedList (); } public void addVertex ( char label ) { vertexlist [ vertexcount ++]= new Vertex ( label ); } public void addEdge ( int i , int j ) { matrixlist [ i ][ j ]= 1 ; matrixlist [ j ][ i ]= 1 ; } public void displayVertex ( int v ) { System . out . println ( vertexlis

How to do Effective Programming?

There is no secret to doing effective programming but following a sequence of steps and procedures can help in building great programs. Today I will take you on a tour to some of the best practices that are integrants of perfect programs. Algorithms are important: - You can’t deny the fact that algorithms are important and before start to write any program, Algorithms are must to write. For example, if there is a program about finding the sum of two numbers? What will you write ?The steps can be :- 1)   Get the first number. 2)   Get the second number. 3)   Add both numbers. This is what algorithm is writing about ,a list of statements .From the above three statements you can conclude boundary cases (at least two number should be there in input), mathematical function(Sum is needed here) , storage capacity(amount of memory to be assign to the variables), number of methods by analyzing repeat steps (reduce replete codes) and many other things. During algorithm only yo