657. 机器人能否返回原点
题目链接:657. 机器人能否返回原点 - 力扣(LeetCode)
题目难度:简单
代码:
class Solution {public boolean judgeCircle(String moves) {int x = 0;int y = 0;for (char c : moves.toCharArray()) {if (c == 'U') y++;if (c == 'D') y--;if (c == 'L') x++;if (c == 'R') x--;}return x == 0 && y == 0;}
}
31. 下一个排列
题目链接:31. 下一个排列 - 力扣(LeetCode)
题目难度:中等
代码:
class Solution {public void nextPermutation(int[] nums) {for (int i = nums.length - 1; i >= 0; i--) {for (int j = nums.length - 1; j > i; j--) {if (nums[j] > nums[i]) {// 交换int temp = nums[i];nums[i] = nums[j];nums[j] = temp;// [i + 1, nums.length) 内元素升序排序Arrays.sort(nums, i + 1, nums.length);return;}}}Arrays.sort(nums); }
}
463. 岛屿的周长
题目链接:463. 岛屿的周长 - 力扣(LeetCode)
题目难度:简单
代码:
class Solution {public int islandPerimeter(int[][] grid) {int landSum = 0; // 陆地数量 int cover = 0; // 相邻陆地数量for (int i = 0; i < grid.length; i++) {for (int j = 0; j < grid[0].length; j++) {if (grid[i][j] == 1) {landSum++;// 统计上面和左边的相邻陆地if(i - 1 >= 0 && grid[i-1][j] == 1) cover++;if(j - 1 >= 0 && grid[i][j-1] == 1) cover++;}}}return landSum * 4 - cover * 2;}
}
1356. 根据数字二进制下 1 的数目排序
题目链接:1356. 根据数字二进制下 1 的数目排序 - 力扣(LeetCode)
题目难度:简单
代码:
class Solution {private int cntInt(int val){int count = 0;while(val > 0) {val = val & (val - 1);count ++;}return count;}public int[] sortByBits(int[] arr) {return Arrays.stream(arr).boxed().sorted(new Comparator<Integer>(){@Overridepublic int compare(Integer o1, Integer o2) {int cnt1 = cntInt(o1);int cnt2 = cntInt(o2);return (cnt1 == cnt2) ? Integer.compare(o1, o2) : Integer.compare(cnt1, cnt2);}}).mapToInt(Integer::intValue).toArray();}
}