Question :201 - 300
# Question :201 - 300
# Q206: 反转链表 (opens new window)
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode node = reverseList(head.next);
head.next.next = head;
head.next = null;
return node;
}
# Q217: 存在重复元素 (opens new window)
public boolean containsDuplicate(int[] nums) {
if (nums.length < 2) {
return false;
}
Set<Integer> set = new HashSet<>();
for(int num : nums) {
if(!set.add(num)){
return true;
}
}
return false;
}
# Q237: 删除链表中的节点 (opens new window)
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
# Q242: 有效的字母异位词 (opens new window)
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()){
return false;
}
int[] arr1 = new int[26], arr2 = new int[26];
char[] sChars1 = s.toCharArray(), sChars2 = t.toCharArray();
for (char c : sChars1) {
arr1[c - 'a'] += 1;
}
for (char c : sChars2) {
arr2[c - 'a'] += 1;
}
for (int i = 0; i < arr1.length; i++) {
if(arr1[i] != arr2[i]) {
return false;
}
}
return true;
}
# Q283: 移动零 (opens new window)
public void moveZeroes(int[] nums){
if (nums == null || nums.length <= 1){
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;
}
}
# Q290: 单词规律 (opens new window)
public boolean wordPattern(String pattern, String s) {
String[] splitArr = s.split(" ");
if(pattern.length() != splitArr.length) {
return false;
}
String[] patLetterArr = new String[26];
Set<String> set = new HashSet<>();
for(int i = 0; i < pattern.length(); i++) {
int index = pattern.charAt(i) - 'a';
String patWord = patLetterArr[index];
String word = splitArr[i];
if (patWord == null){
if(set.contains(word)) {
return false;
}
set.add(word);
patLetterArr[index] = word;
}else if (!patWord.equals(word)){
return false;
}
}
return true;
}
上次更新: 5/21/2023, 11:34:33 PM