
解题代码
class Solution { public int maxDistance(int[] colors) { Map<Integer,int[]> map = new HashMap<>(2); List<int[]> l = new ArrayList<>(); for(int i = 0; i < colors.length; i++) { int [] ints = new int[2]; if(map.containsKey(colors[i])) { map.get(colors[i])[1] = i; //更新最大值 } else { map.put(colors[i],new int[]{i,i}); } } for (Integer key : map.keySet()) { l.add(map.get(key)); } int max = 0; for(int i = 0; i < l.size(); i++ ) { for(int j = i + 1; j < l.size(); j++ ) { max = Math.max(Math.abs(l.get(i)[1] - l.get(j)[0] ),max ); max = Math.max(Math.abs(l.get(j)[1] - l.get(i)[0] ),max ); } } return max; }}
class Solution { public int maxDistance(int[] colors) { int length = colors.length; int max = 0; //记录最大值 for(int i = 0; i < length; i++) { for(int j = i + 1; j < length; j++) { if(colors[i] != colors[j]) { max = Math.max(max,j - i); } } } return max; }}
class Solution { public int maxDistance(int[] cs) { int len = cs.length; //记录长度 /** 因为要最大,所以有三种情况: 首尾不相同直接返回,否则说明首尾是相同的颜色 “0~右往左第一个不相同”这一段 “左往右第一个不相同~length-1”这一段 然后比较这两个谁大就行 */ //此处采用贪心 if(cs[0] != cs[len - 1]) return len - 1; int left = 1; while( cs[0] == cs[left]) left++; //更新左边界 int right = len - 2; while(cs[len - 1] == cs[right] ) right--; //更新右边界 return Math.max(right,len - 1 - left); }}