LeetCode75. 颜色分类+LeetCode49. 字母异位词分组

思路

直接用选择排序就可以了。归并排序不能用,归并排序会单独申请一个数组。

代码

class Solution {
    public void sortColors(int[] nums) {
        int min = 0;
        for(int i = 0;i<nums.length-1;i++){
            min = i;
            for(int j = i+1;j<nums.length;j++){
                min = nums[min]>nums[j]?j:min;
            }
            swap(nums,i,min);
       }

    }
    //交换两个元素
	public static void swap(int[] arr, int i, int j) {
		int tmp = arr[i];
		arr[i] = arr[j];
		arr[j] = tmp;
	}
}

49. 字母异位词分组

思路

这个题就是用List和Map求解即可,在每次装入的是否要对其进行判断看是否是相同的字母。

有两个方法判断一个是用我的Sort排序,一个是用哈希表。

代码

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> res = new ArrayList<List<String>>();
        if(strs == null || strs.length == 0){
            return res;
        }
        HashMap<String,Integer> map = new HashMap<>();
        for(String str:strs){
            char[] ch = str.toCharArray();
            Arrays.sort(ch);
            String s = new String(ch);
            if(map.containsKey(s)){
                List list = new ArrayList();
                list = res.get(map.get(s));
                list.add(str);
            }else{
                List list = new ArrayList();
                list.add(str);
                map.put(s,res.size());
                res.add(list);
            }
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_56640241/article/details/125171469
今日推荐