One day three questions Leetcode (C++&java) -1~3

Source: Internet
Author: User
Tags repetition

Reprint please specify the source:

Http://blog.csdn.net/miaoyunzexiaobao



1. The Sum of the

https://leetcode.com/problems/two-sum/

given an array, in which two numbers are found, so that the sum of two numbers is the given Target . Returns the position of the two numbers in the array. The position of two digits is indicated by index1 and index2 , and requires index1<index2. Example:

Input: numbers={2, 7, one, a, target=9
Output: Index1=1, index2=2

Ideas:

UseMapthe characteristics of whichMapof the(Key,value)Representative(target-num[i],i), i.e.Keyrepresents a numberNum[i]to theTargetthe distance,valuerepresents a numberNum[i]The position in the array. TraverseNumeach number in the array to detect whether the number isMapof theKeyIf the search succeeds, the number is savedMap, continue to view the next number. Take the input output given in the question as an example:

i 0 map is empty, numbers[0]=2 target-numbers[i] = 9–2 = 7 numbers[0] 7 target-9 (7 0) join map

I to be 1 when the numbers[1]=7 , Map of the Key contains the number, the query succeeds.

The number of two queries to the numbers The subscript in is { 0 , 1 }. Since index is calculated starting from 1 , it returns {1,2 }

C++:

Vector<int> twosum (vector<int> &numbers, int target) {   <span style= "White-space:pre" ></ span>vector<int> result;        int index1=0,index2=0;        Map<int,int> mInt;         For (Vector<int>::iterator iter =numbers.begin (); ITER! = Numbers.end (); ++iter) {               if (mint.find)! = Mint.end ()) {                      index1 = (Mint.find (*iter))->second + 1;                      Index2 = Iter-numbers.begin () +1;               } else                      Mint.insert (Make_pair (target-*iter,iter-numbers.begin ()));        }        cout<<index1<< "" <<index2<<endl;        Result.push_back (index1);        Result.push_back (INDEX2);        return result;}

Java:

Public int[] Twosum (int[] numbers, int target) {int[] result = new Int[2];        int index1 = 0, index2 = 0;        Map<integer, integer> map = Newhashmap<integer, integer> ();        for (int i = 0; i < numbers.length;++i) {               if (Map.containskey (Numbers[i])) {                      index1 =map.get (numbers[i]) + 1;
   index2 = i + 1;                      break;               } else                      Map.put (target-numbers[i], i);        }        Result[0] = index1;        RESULT[1] = Index2;        return result;   }

2. Add the Numbers

https://leetcode.com/problems/add-two-numbers/

Given two numbers stored in reverse order in the linked list, the number of two numbers is calculated and exported in Reverse Chain list form. Cases:

Given 342 and 564, two numbers and 807. That is, input (2, 4, 3) and (5, 6, 4), which requires output 7, 0, 8:

Input: (2, 4, 3) + (5, 6, 4)
Output: 7-> 0-8

Ideas:

This problem is not difficult, the two linked list of each number in turn, the process of attention to the sum of two of a node is greater than Ten add one to the two-number addition of the next node.

C++:

ListNode *addtwonumbers (ListNode *l1, ListNode *l2) {<span style= "white-space:pre" ></span>listnode * result = new ListNode (0);        ListNode *cur = result;        int count = 0;        while (L1! = NULL | | L2! = NULL) {               int i = 0, j = 0;               if (L1! = NULL) {                      i = l1->val;                      L1 = l1->next;               }               if (L2! = NULL) {                      j = l2->val;                      L2 = l2->next;               }               int sum = i + j + count;               Cur->next = new ListNode (sum%10);               cur = cur->next;               Count = Sum  /ten;        }        if (count! = 0)               Cur->next = Newlistnode (count);        Return result->next; }

Java:

Public Listnodeaddtwonumbers (ListNode L1, ListNode L2) {<span style= "White-space:pre" ></span>listnode result = new ListNode (0); <span style= "White-space:pre" ></span>listnode cur = result;        int count = 0;        while (L1! = NULL | | L2! = NULL) {               int i = 0, j = 0;               if (L1! = null) {                      i = l1.val;                      L1 = L1.next;               }               if (L2! = null) {                      j = l2.val;                      L2 = L2.next;               }               int sum = i + j + count;               Cur.next = new ListNode (sum%10);               cur = cur.next;               Count = SUM/10;        }        if (count! = 0)               cur.next = new ListNode (count);        return result.next;}

3. Longest Substring withoutrepeating characters

https://leetcode.com/problems/longest-substring-without-repeating-characters/

given a string, the longest non-repeating subsequence length is obtained. Example: the input string "ABCABCBB", whose longest non-repeating subsequence is ABC, returns 2. The input string "bbbb", whose longest non-repeating subsequence is b, returns 1.

Ideas:

the question is of some meaning. Available with two pointers, a head pointing to the current substring, a pointing tail, and a tail pointer runner continuously, when there is a character in front of it, records the current substring length and the optimal solution comparison results. After the tail pointer runner temporarily remain motionless, move the head pointer to the next and the tail pointer does not repeat the place, and then continue to move the tail pointer runner, start a new round of non-repeating substring length calculation. That is, the head pointer Walker keeps scanning backwards until a character is scanned and the tail finger runner the same after adding one, then the tail pointer runner continue to scan backwards. The algorithm ends when the tail pointer runner reaches the end of the string. The complexity of O (n) + O (n) = O (n).

instring s = "adbcabed"For example, in meeting the first repetition of aaits maximum non-repeating substring length is4.at thisWalkerin theS[0],runnerin theS[4], the length of this non-repeating substring is4.will thenWalkermove toD, i.e.S[1]. Will beRunnercontinue backwards later. WhenRunnermove to a secondb, i.e.S[5]repetition occurs again, the length of the substring is4.will beWalkermove to thebafter the character, i.e.C,alsoS[3],Runnercontinue backwards until there are no duplicate elements at the end,RunnerPointingsthe last elementDafter the position, get the maximum length8–3 = 5;

C++:

int lengthoflongestsubstring (string s) {        int maxLength = 0;        int Walker = 0, runner = 0;        Set<char> SetChar;         for (int i = 0; i < s.length (); ++i) {               if (Setchar.find (S[i]) ==setchar.end ())                      Setchar.insert (S[i]);               else{                      maxLength = (maxlength> runner-walker)? ( MaxLength):(runner-walker);                      while (S[walker]!=s[runner]) {                             setchar.erase (*setchar.find (S[walker]));                             ++walker;                      }                      ++walker;               }                                  ++runner;        }        MaxLength = (MaxLength > Runner-walker)? (maxLength):(runner-walker);        return maxLength;}

Java:

public int lengthoflongestsubstring (String s) {  <span style= "White-space:pre" ></span>int maxLength = 0 ;        int Walker = 0, runner = 0;        set<character> SetChar = newhashset<character> ();        for (int i = 0; i < s.length (); ++i) {               if (!setchar.contains (S.charat (i)))                      Setchar.add (S.charat (i));               else {                      maxLength =math.max (maxLength, runner-walker);                      while (S.charat (Walker)!=s.charat (runner)) {                             setchar.remove (Walker));                             ++walker;                      }                      ++walker;               }               ++runner;        }        MaxLength = Math.max (MaxLength, runner-walker);        return maxLength;}


One day three questions Leetcode (C++&java) -1~3

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.