File tree Expand file tree Collapse file tree 2 files changed +88
-0
lines changed Expand file tree Collapse file tree 2 files changed +88
-0
lines changed Original file line number Diff line number Diff line change 1+ You are given two linked lists representing two non -negative numbers . The digits are stored in reverse order and each of their nodes contain a single digit . Add the two numbers and return it as a linked list .
2+
3+ Input : (2 -> 4 -> 3 ) + (5 -> 6 -> 4 )
4+ Output : 7 -> 0 -> 8
5+
6+ /**
7+ * Definition for singly-linked list.
8+ * public class ListNode {
9+ * int val;
10+ * ListNode next;
11+ * ListNode(int x) {
12+ * val = x;
13+ * next = null;
14+ * }
15+ * }
16+ */
17+ public class Solution {
18+ public ListNode addTwoNumbers (ListNode l1 , ListNode l2 ) {
19+ if (l1 == null ) return l2 ;
20+ if (l2 == null ) return l1 ;
21+ ListNode head = new ListNode (0 );
22+ ListNode cur = head ;
23+ int plus = 0 ;
24+ while (l1 != null && l2 != null ) {
25+ int sum = l1 .val + l2 .val + plus ;
26+ plus = sum / 10 ;
27+ sum = sum % 10 ;
28+ cur .next = new ListNode (sum );
29+ cur = cur .next ;
30+ l1 = l1 .next ;
31+ l2 = l2 .next ;
32+ }
33+ if (l1 != null ) {
34+ if (plus != 0 ) {
35+ cur .next = addTwoNumbers (l1 , new ListNode (plus ));
36+ } else {
37+ cur .next = l1 ;
38+ }
39+ } else if (l2 != null ) {
40+ if (plus != 0 ) {
41+ cur .next = addTwoNumbers (l2 , new ListNode (plus ));
42+ } else {
43+ cur .next = l2 ;
44+ }
45+ } else if (plus != 0 ) {
46+ cur .next = new ListNode (plus );
47+ }
48+
49+ return head .next ;
50+ }
51+ }
Original file line number Diff line number Diff line change 1+ Implement next permutation , which rearranges numbers into the lexicographically next greater permutation of numbers .
2+
3+ If such arrangement is not possible , it must rearrange it as the lowest possible order (ie , sorted in ascending order ).
4+
5+ The replacement must be in -place , do not allocate extra memory .
6+
7+ Here are some examples . Inputs are in the left -hand column and its corresponding outputs are in the right -hand column .
8+ 1 ,2 ,3 ¡ú 1 ,3 ,2
9+ 3 ,2 ,1 ¡ú 1 ,2 ,3
10+ 1 ,1 ,5 ¡ú 1 ,5 ,1
11+
12+ public class Solution {
13+ public void nextPermutation (int [] num ) {
14+ int i1 = 0 ;
15+ int i2 = 0 ;
16+ int i = num .length - 1 ;
17+ int j = 0 ;
18+ while (i > 0 && num [i - 1 ] >= num [i ]) {
19+ i --;
20+ }
21+ if (i == 0 ) {
22+ Arrays .sort (num );
23+ return ;
24+ } else {
25+ i1 = i - 1 ;
26+ }
27+ j = i1 + 1 ;
28+ while (j < num .length && num [i1 ] < num [j ]) {
29+ j ++;
30+ }
31+ i2 = j - 1 ;
32+ int temp = num [i1 ];
33+ num [i1 ] = num [i2 ];
34+ num [i2 ] = temp ;
35+ Arrays .sort (num , i1 + 1 , num .length );
36+ }
37+ }
You can’t perform that action at this time.
0 commit comments