11.16日
406.根据身高重建队列
class Solution {
public int[][] reconstructQueue(int[][] people) {
// 按照身高降序排序,如果身高一样,则按照排在这个人前面的人数升序排序
Arrays.sort(people, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if (o1[0] == o2[0]) {
return o1[1] - o2[1];
} else {
return o2[0] - o1[0];
}
}
});
List<int[]> list = new ArrayList<>();
for(int[] i : people) {
list.add(i[1], i);
}
int[][] ans = list.toArray(new int[list.size()][]);
return ans;
}
}
11.17日
1030.距离顺序排序矩阵单元格
class Solution {
public int[][] allCellsDistOrder(int R, int C, int r0, int c0) {
int[][] ret = new int[R * C][2];
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
ret[i * C + j] = new int[]{i, j};
}
}
Arrays.sort(ret, (int[] a, int[] b) -> {
return (abs(a[0] - r0) + abs(a[1] - c0)) - (abs(b[0] - r0) + abs(b[1] - c0));
});
return ret;
}
public int abs(int n) {
return n >= 0 ? n : n * -1;
}
}
11.18日
134.加油站
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int now = 0, all = 0, start = 0;
for(int i = 0; i < gas.length; i ++) {
now = now + gas[i] - cost[i];
all = all + gas[i] - cost[i];
if(now < 0) {
start = i + 1;
now = 0;
}
}
return all >= 0 ? start : -1;
}
}
11.19日
283.移动零
class Solution {
public void moveZeroes(int[] nums) {
if(nums == null || nums.length < 2) {
return;
}
int index = 0;
for(int i = 0; i < nums.length; i ++) {
if (nums[i] != 0) {
nums[index] = nums[i];
index++;
}
}
for(int i = index; i < nums.length; i ++) {
nums[i] = 0;
}
}
}
11.20日
147.对链表进行插入排序
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode node = new ListNode(0), pre;
node.next = head;
while(head != null && head.next != null) {
if(head.val <= head.next.val) {
head = head.next;
continue;
}
pre = node;
while (pre.next.val < head.next.val){
pre = pre.next;
}
ListNode temp = head.next;
head.next = temp.next;
temp.next = pre.next;
pre.next = temp;
}
return node.next;
}
}
11.22日
242.有效的字母异位词
class Solution {
public boolean isAnagram(String s, String t) {
char[] ss = s.toCharArray();
char[] tt = t.toCharArray();
if(ss.length != tt.length) {
return false;
}
int[] arrs = new int[26];
int[] arrt = new int[26];
for(int i = 0; i < ss.length; i ++) {
arrs[ss[i] - 'a'] ++;
arrt[tt[i] - 'a'] ++;
}
for(int i = 0; i < 26; i ++) {
if(arrs[i] != arrt[i]) {
return false;
}
}
return true;
}
}
7万+

被折叠的 条评论
为什么被折叠?



