Exercise daily algorithm (2020-1-11)

 

 

This question is accomplished using double pointer

Time complexity is O (N ^ 2)

package com.example.demo09;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

public class ThreeNumberSum {
    public static List<List<Integer>> threeSum(int[] nums)
    {
        List<List<Integer>> list=new ArrayList<>();
        int len=nums.length;
        if (nums==null||len<3)
        {
            return list;
        }
        //Arrays.sort underlying optimization using fast discharge 
        Arrays.sort (the nums);
         for ( int I = 0; I <len; I ++ ) 
        { 
            IF (the nums [I]> 0 ) 
            { 
                BREAK ; // if the current value of the is greater than 0, and the sum of the three must be greater than 0, because the sorting, the first number is minimum will 
            }
             IF (I> 0 && the nums [I] == the nums [-I. 1 ]) {
                 Continue ; // deduplication 
            }
             int L = I +. 1 ;
             int R & lt-len =. 1 ;
             the while (L < R & lt) {
                 int SUM = the nums [I] the nums + [L] + nums[R];
                if (sum == 0) {
                    list.add(Arrays.asList(nums[i], nums[L], nums[R]));
                    while (L < R && nums[L] == nums[L + 1]) L++; // 去重
                    while (L < R && nums[R] == nums[R - 1]) R--; // 去重
                    L++;
                    R--;
                } else {
                    if (sum < 0) {
                        L++;
                    } else {
                        R--;
                    }
                }
            }
        }
        return list;
    }
} 

 

Use greedy algorithm

package com.example.demo09;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class LuMaNumberTransaction {
    //使用贪心法
    public static int transaction(String  str)
    {
        Map<String,Integer> map=new HashMap<>();
        int num=0;
        map.put("I",1);
        map.put("X",10);
        map.put("C",100);
        map.put("M",1000);
        map.put("V",5);
        map.put("L",50);
        map.put("D",500);
        map.put("IV",4);
        map.put("IX",9);
        map.put("XL",40);
        map.put("XC",90);
        map.put("CD",400);
        map.put("CM",900);
        for(int i=0;i<str.length();i++)
        {
            String string = null;
            if(i+1<str.length())
           {
              string=str.substring(i,i+2);
            }
           Integer x=map.get(string);
            if (x==null) {
                string = str.substring(i, i + 1);
                x=map.get(string);
                num+=x;
        }else{
                num+=x;
                i++;
            }
        }
        return num;
    }

}

Guess you like

Origin www.cnblogs.com/qyx66/p/12180786.html