每日算法练习(2020-1-11)

使用双指针来完成这道题

时间复杂度为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底层使用的是优化的快排
        Arrays.sort(nums);
        for(int i=0;i<len;i++)
        {
            if(nums[i]>0)
            {
                break;//如果当前的值大于0,则三数之和一定大于0,因为排序了,第一个数必为最小的
            }
            if(i>0&&nums[i]==nums[i-1]) {
                continue;//去重
            }
            int L=i+1;
            int R=len-1;
            while (L<R) {
                int sum = nums[i] + 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;
    }
} 

 

使用贪心算法

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;
    }

}

猜你喜欢

转载自www.cnblogs.com/qyx66/p/12180786.html
今日推荐