Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
思路
A->B->C->D
原本要删除B,知道A,只需要A.next= B.next;
现在只提供B,无法提供 A 时只能把 C 复制到 B,然后删除 C 即可。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ publicclassSolution{ publicvoiddeleteNode(ListNode node){ node.val = node.next.val; node.next = node.next.next; } }
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.
For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).
Note: You may assume that n is not less than 2 and not larger than 58.
Hint:
There is a simple O(n) solution to this problem. You may check the breaking results of n ranging from 7 to 10 to discover the regularities.
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have n versions [1, 2, …, n] and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
找出最先坏的版本。
思路
二分法查询。主要要注意的是mid = head + (tail - head)/2。假如使用head + tail 会越界。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* The isBadVersion API is defined in the parent class VersionControl. boolean isBadVersion(int version); */
publicclassSolutionextendsVersionControl{ publicintfirstBadVersion(int n){ int head = 1;int tail = n; while(!isBadVersion(head) && head <= tail){ int mid = head + (tail - head)/2; if(isBadVersion(mid)){ tail = mid -1; }else{ head = mid + 1; } } return head; } }