NC_35_EDIT_COST NC_36_findMedianinTwoSortedAray NC_37_MERGEINTERVAL
package org.example.interview.practice; /** * @author xianzhe.ma * @date 2021/11/6 */ public class NC_36_findMedianinTwoSortedAray { public int findMedianinTwoSortedAray (int[] arr1, int[] arr2) { // write code here int finalPos = arr1.length; int firstIndex = 0; int secondIndex = 0; if (finalPos == 1) { return Math.min(arr1[0], arr2[0]); } int tag = -1;//0 first 1 second while (firstIndex + secondIndex < finalPos) { if (arr1[firstIndex] <= arr2[secondIndex]) { firstIndex++; tag = 0; } else { secondIndex++; tag = 1; } } if (tag == 0) { return arr1[firstIndex-1]; } else { return arr2[secondIndex-1]; } } }
package org.example.interview.practice; import java.util.ArrayList; import java.util.Comparator; /** * @author xianzhe.ma * @date 2021/7/27 */ public class NC_37_MERGEINTERVAL { public static class Interval { int start; int end; Interval() { start = 0; end = 0; } Interval(int s, int e) { start = s; end = e; } } public ArrayList<Interval> merge(ArrayList<Interval> intervals) { intervals.sort(new Comparator<Interval>() { @Override public int compare(Interval o1, Interval o2) { return o1.start - o2.start; } }); ArrayList<Interval> ans = new ArrayList<Interval>(); int len = intervals.size(); if (len == 0) return ans; for (int i = 1; i < len; i++) { if (intervals.get(i).start <= intervals.get(i - 1).end) { intervals.get(i).start = Math.min(intervals.get(i - 1).start, intervals.get(i).start); intervals.get(i).end = Math.max(intervals.get(i - 1).end, intervals.get(i).end); } else { ans.add(intervals.get(i - 1)); } } ans.add(intervals.get(len - 1)); return ans; } }
描述 给定两个字符串str1和str2,再给定三个整数ic,dc和rc,分别代表插入、删除和替换一个字符的代价,请输出将str1编辑成str2的最小代价。 public class NC_35_EDIT_COST{ /** * min edit cost * @param str1 string字符串 the string * @param str2 string字符串 the string * @param ic int整型 insert cost * @param dc int整型 delete cost * @param rc int整型 replace cost * @return int整型 */ public int minEditCost (String str1, String str2, int ic, int dc, int rc) { // write code here int len1 = str1.length(); int len2 = str2.length(); //dp[i][j]不包含第i个字符和第j个字符,因此需要+1 int[][] dp = new int[len1+1][len2+1]; //矩阵第一行表示空字符串转为str2的代价,插入j个字符 for(int j = 1; j <= len2; j++) { dp[0][j] = j * ic; } //矩阵第1列表示str1转为空字符串的代价,删除i个字符 for(int i = 1; i <= len1; i++) { dp[i][0] = i * dc; } for(int i = 1; i <= len1; i++) { for(int j = 1; j <= len2; j++) { if(str1.charAt(i-1) == str2.charAt(j-1)) { dp[i][j] = dp[i-1][j-1]; } else { dp[i][j] = Math.min(dp[i][j-1] + ic, dp[i-1][j] + dc); dp[i][j] = Math.min(dp[i][j], dp[i-1][j-1] + rc); } } } return dp[len1][len2]; } }