记录一下最近刷的几道题。
20. Valid Parentheses
-
题目20
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
-
分析
由于当时学过数据结构课程,所以这道题自然就想到用栈去解决。最开始的代码写的麻烦,就是判断当前栈顶的元素和读取符号是否匹配。匹配则出栈,否则入栈。最后通过栈是否为空判断结果。别人用的栈刚好和我的相反,设计的很巧妙。
-
自己的代码
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
if(s==null || s.length() %2 !=0)
return false;
else
for(int i=0;i<s.length();i++){
if(stack.isEmpty()){
stack.push(s.charAt(i));
}else if((stack.peek()=='(' && s.charAt(i) == ')')||
(stack.peek()=='[' && s.charAt(i) == ']')||
(stack.peek()=='{' && s.charAt(i) == '}')
){
stack.pop();
}else{
stack.push(s.charAt(i));
}
}
if(stack.isEmpty())
return true;
else
return false;
}
}
-
别人的代码
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}
}
21. Merge Two Sorted Lists
-
题目21
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
-
分析
这道题也是数据结构的例题,分情况讨论即可。
-
自己的代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = null;
ListNode temp = null;
if(l1==null)
return l2;
if(l2==null)
return l1;
if(l1.val<=l2.val){
head=l1;
l1=l1.next;
}else{
head=l2;
l2=l2.next;
}
temp = head;
while(l1!=null && l2!=null){
if(l1.val<=l2.val){
temp.next = l1;
l1 = l1.next;
}else{
temp.next = l2;
l2 = l2.next;
}
temp = temp.next;
}
if(l1!=null){
temp.next = l1;
}else{
temp.next =l2;
}
return head;
}
}
26. Remove Duplicates from Sorted Array
-
题目26
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,2],Your function should return length =2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],Your function should return length = 5, with the first five elements of numsbeing modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
-
分析
利用两个“指针”进行遍历数组,不断移动即可。和27题很像。
-
自己的代码
class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length == 0) return 0;
int i = 0;
for(int j=1;j<nums.length;j++){
if(nums[j]!=nums[i]){
i++;
nums[i]=nums[j];
}
}
return i+1;
}
}
-
别人的代码
class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length <= 1) { return nums.length;}
int offset = 0;
for (int i=1; i<nums.length; i++) {
if (nums[i] == nums[i-1]) {
offset--;
} else {
nums[i+offset] = nums[i];
}
}
return nums.length + offset;
}
}
27. Remove Element
-
题目27
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example 1:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,1,2,2,3,0,4,2], val = 2,Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
Note that the order of those five elements can be arbitrary.
It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
-
分析
最开始我利用2重循环来处理,没有利用两个“指针”,但时间上反而我的是最快的。别的代码都是一重循环,结果运行时间更久。发现程序稍微改一点运行时间就不同。这道题和26题很相似。
-
自己的代码
class Solution {
public int removeElement(int[] nums, int val) {
if(nums.length==0) return 0;
int index=0;
int i=0,j=0;
while(i<nums.length){
if(nums[i]==val){//当前数字和要寻找的数字相同
for(j=i+1;j<nums.length;j++){//遍历数组后面元素,寻找不同的数字
if(nums[j]!=val){
nums[index++] = nums[j];
i=j+1;
break;
}
}
if(j==nums.length){//没有找到不同数,结束
return index;
}
}else{//当前数字和要寻找的数字不同
nums[index++] = nums[i++];
}
}
return index;
}
}
-
别人的代码
class Solution {
public int removeElement(int[] nums, int val) {
int i = 0;
for (int j = 0; j < nums.length; j++) {
if (nums[j] != val) {
nums[i] = nums[j];
i++;
}
}
return i;
}
}
class Solution {
public int removeElement(int[] nums, int val) {
int i = 0;
int n = nums.length;
while (i < n) {
if (nums[i] == val) {
nums[i] = nums[n - 1];
// reduce array size by one
n--;
} else {
i++;
}
}
return n;
}
}